readFile.js 916 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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;