readFile.js 916 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //
  2. 'use strict';
  3. const fs = require('fs');
  4. function readFile(filepath , options ) {
  5. options = options || {};
  6. const throwNotFound = options.throwNotFound || false;
  7. return new Promise((resolve, reject) => {
  8. fs.readFile(filepath, 'utf8', (err, content) => {
  9. if (err && err.code === 'ENOENT' && !throwNotFound) {
  10. return resolve(null);
  11. }
  12. if (err) return reject(err);
  13. resolve(content);
  14. });
  15. });
  16. }
  17. readFile.sync = function readFileSync(
  18. filepath ,
  19. options
  20. ) {
  21. options = options || {};
  22. const throwNotFound = options.throwNotFound || false;
  23. try {
  24. return fs.readFileSync(filepath, 'utf8');
  25. } catch (err) {
  26. if (err.code === 'ENOENT' && !throwNotFound) {
  27. return null;
  28. }
  29. throw err;
  30. }
  31. };
  32. module.exports = readFile;