SyncAsyncFileSystemDecorator.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("./Resolver").FileSystem} FileSystem */
  7. /** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */
  8. /**
  9. * @param {SyncFileSystem} fs file system implementation
  10. * @constructor
  11. */
  12. function SyncAsyncFileSystemDecorator(fs) {
  13. this.fs = fs;
  14. this.lstat = undefined;
  15. this.lstatSync = undefined;
  16. const lstatSync = fs.lstatSync;
  17. if (lstatSync) {
  18. this.lstat = (arg, options, callback) => {
  19. let result;
  20. try {
  21. result = lstatSync.call(fs, arg);
  22. } catch (e) {
  23. return (callback || options)(e);
  24. }
  25. (callback || options)(null, result);
  26. };
  27. this.lstatSync = (arg, options) => lstatSync.call(fs, arg, options);
  28. }
  29. this.stat = (arg, options, callback) => {
  30. let result;
  31. try {
  32. result = callback ? fs.statSync(arg, options) : fs.statSync(arg);
  33. } catch (e) {
  34. return (callback || options)(e);
  35. }
  36. (callback || options)(null, result);
  37. };
  38. this.statSync = (arg, options) => fs.statSync(arg, options);
  39. this.readdir = (arg, options, callback) => {
  40. let result;
  41. try {
  42. result = fs.readdirSync(arg);
  43. } catch (e) {
  44. return (callback || options)(e);
  45. }
  46. (callback || options)(null, result);
  47. };
  48. this.readdirSync = (arg, options) => fs.readdirSync(arg, options);
  49. this.readFile = (arg, options, callback) => {
  50. let result;
  51. try {
  52. result = fs.readFileSync(arg);
  53. } catch (e) {
  54. return (callback || options)(e);
  55. }
  56. (callback || options)(null, result);
  57. };
  58. this.readFileSync = (arg, options) => fs.readFileSync(arg, options);
  59. this.readlink = (arg, options, callback) => {
  60. let result;
  61. try {
  62. result = fs.readlinkSync(arg);
  63. } catch (e) {
  64. return (callback || options)(e);
  65. }
  66. (callback || options)(null, result);
  67. };
  68. this.readlinkSync = (arg, options) => fs.readlinkSync(arg, options);
  69. this.readJson = undefined;
  70. this.readJsonSync = undefined;
  71. const readJsonSync = fs.readJsonSync;
  72. if (readJsonSync) {
  73. this.readJson = (arg, options, callback) => {
  74. let result;
  75. try {
  76. result = readJsonSync.call(fs, arg);
  77. } catch (e) {
  78. return (callback || options)(e);
  79. }
  80. (callback || options)(null, result);
  81. };
  82. this.readJsonSync = (arg, options) => readJsonSync.call(fs, arg, options);
  83. }
  84. }
  85. module.exports = SyncAsyncFileSystemDecorator;