source: trip-planner-front/node_modules/read-cache/index.js@ b738035

Last change on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.5 KB
RevLine 
[6a3a178]1var fs = require('fs');
2var path = require('path');
3var pify = require('pify');
4
5var stat = pify(fs.stat);
6var readFile = pify(fs.readFile);
7var resolve = path.resolve;
8
9var cache = Object.create(null);
10
11function convert(content, encoding) {
12 if (Buffer.isEncoding(encoding)) {
13 return content.toString(encoding);
14 }
15 return content;
16}
17
18module.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
42module.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
68module.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
76module.exports.clear = function () {
77 cache = Object.create(null);
78};
Note: See TracBrowser for help on using the repository browser.