fs/lib/fsInterface.js

  1. function toPosix(inputPath) {
  2. return inputPath.replace(/\\/g, "/");
  3. }
  4. /**
  5. * Wraps readers to access them through a [Node.js fs]{@link https://nodejs.org/api/fs.html} styled interface.
  6. *
  7. * @public
  8. * @alias module:@ui5/fs.fsInterface
  9. * @param {module:@ui5/fs.AbstractReader} reader Resource Reader or Collection
  10. *
  11. * @returns {object} Object with [Node.js fs]{@link https://nodejs.org/api/fs.html} styled functions
  12. * [<code>readFile</code>]{@link https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback},
  13. * [<code>stat</code>]{@link https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback},
  14. * [<code>readdir</code>]{@link https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback} and
  15. * [<code>mkdir</code>]{@link https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback}
  16. */
  17. module.exports = (reader) => {
  18. return {
  19. readFile(fsPath, options, callback) {
  20. if (typeof options === "function") {
  21. callback = options;
  22. options = undefined;
  23. }
  24. if (typeof options === "string") {
  25. options = {encoding: options};
  26. }
  27. const posixPath = toPosix(fsPath);
  28. reader.byPath(posixPath, {
  29. nodir: false
  30. }).then(function(resource) {
  31. if (!resource) {
  32. const error = new Error(`ENOENT: no such file or directory, open '${fsPath}'`);
  33. error.code = "ENOENT"; // "File or directory does not exist"
  34. callback(error);
  35. return;
  36. }
  37. return resource.getBuffer().then(function(buffer) {
  38. let res;
  39. if (options && options.encoding) {
  40. res = buffer.toString(options.encoding);
  41. } else {
  42. res = buffer;
  43. }
  44. callback(null, res);
  45. });
  46. }).catch(callback);
  47. },
  48. stat(fsPath, callback) {
  49. const posixPath = toPosix(fsPath);
  50. reader.byPath(posixPath, {
  51. nodir: false
  52. }).then(function(resource) {
  53. if (!resource) {
  54. const error = new Error(`ENOENT: no such file or directory, stat '${fsPath}'`);
  55. error.code = "ENOENT"; // "File or directory does not exist"
  56. callback(error);
  57. } else {
  58. callback(null, resource.getStatInfo());
  59. }
  60. }).catch(callback);
  61. },
  62. readdir(fsPath, callback) {
  63. let posixPath = toPosix(fsPath);
  64. if (!posixPath.match(/\/$/)) {
  65. // Add trailing slash if not present
  66. posixPath += "/";
  67. }
  68. reader.byGlob(posixPath + "*", {
  69. nodir: false
  70. }).then((resources) => {
  71. const files = resources.map((resource) => {
  72. return resource._name;
  73. });
  74. callback(null, files);
  75. }).catch(callback);
  76. },
  77. mkdir(fsPath, callback) {
  78. setTimeout(callback, 0);
  79. }
  80. };
  81. };