index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. var fs = require('fs');
  2. var path = require('path');
  3. var pify = require('pify');
  4. var stat = pify(fs.stat);
  5. var readFile = pify(fs.readFile);
  6. var resolve = path.resolve;
  7. var cache = Object.create(null);
  8. function convert(content, encoding) {
  9. if (Buffer.isEncoding(encoding)) {
  10. return content.toString(encoding);
  11. }
  12. return content;
  13. }
  14. module.exports = function (path, encoding) {
  15. path = resolve(path);
  16. return stat(path).then(function (stats) {
  17. var item = cache[path];
  18. if (item && item.mtime.getTime() === stats.mtime.getTime()) {
  19. return convert(item.content, encoding);
  20. }
  21. return readFile(path).then(function (data) {
  22. cache[path] = {
  23. mtime: stats.mtime,
  24. content: data
  25. };
  26. return convert(data, encoding);
  27. });
  28. }).catch(function (err) {
  29. cache[path] = null;
  30. return Promise.reject(err);
  31. });
  32. };
  33. module.exports.sync = function (path, encoding) {
  34. path = resolve(path);
  35. try {
  36. var stats = fs.statSync(path);
  37. var item = cache[path];
  38. if (item && item.mtime.getTime() === stats.mtime.getTime()) {
  39. return convert(item.content, encoding);
  40. }
  41. var data = fs.readFileSync(path);
  42. cache[path] = {
  43. mtime: stats.mtime,
  44. content: data
  45. };
  46. return convert(data, encoding);
  47. } catch (err) {
  48. cache[path] = null;
  49. throw err;
  50. }
  51. };
  52. module.exports.get = function (path, encoding) {
  53. path = resolve(path);
  54. if (cache[path]) {
  55. return convert(cache[path].content, encoding);
  56. }
  57. return null;
  58. };
  59. module.exports.clear = function () {
  60. cache = Object.create(null);
  61. };