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