Skip to content

Commit f285d11

Browse files
committed
feat: cache precision per device
See #103
1 parent 9f8c303 commit f285d11

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

lib/mtime-precision.js

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,40 +3,48 @@
33
const cacheSymbol = Symbol();
44

55
function probe(file, fs, callback) {
6-
const cachedPrecision = fs[cacheSymbol];
6+
let cachedPrecisions = fs[cacheSymbol];
7+
if (cachedPrecisions === undefined) {
8+
cachedPrecisions = new Map();
79

8-
if (cachedPrecision) {
9-
return fs.stat(file, (err, stat) => {
10-
/* istanbul ignore if */
11-
if (err) {
12-
return callback(err);
13-
}
14-
15-
callback(null, stat.mtime, cachedPrecision);
16-
});
10+
// Cache the precisions in a non-enumerable way
11+
Object.defineProperty(fs, cacheSymbol, { value: cachedPrecisions });
1712
}
1813

19-
// Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
20-
const mtime = new Date((Math.ceil(Date.now() / 1000) * 1000) + 5);
21-
22-
fs.utimes(file, mtime, mtime, (err) => {
14+
return fs.stat(file, (err, stat) => {
2315
/* istanbul ignore if */
2416
if (err) {
2517
return callback(err);
2618
}
2719

28-
fs.stat(file, (err, stat) => {
20+
const dev = stat.dev;
21+
22+
// Precisions are cached by device, see #103
23+
const precision = cachedPrecisions.get(dev);
24+
if (precision !== undefined) {
25+
return callback(null, stat.mtime, precision);
26+
}
27+
28+
// Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
29+
const mtime = new Date((Math.ceil(Date.now() / 1000) * 1000) + 5);
30+
31+
fs.utimes(file, mtime, mtime, (err) => {
2932
/* istanbul ignore if */
3033
if (err) {
3134
return callback(err);
3235
}
3336

34-
const precision = stat.mtime.getTime() % 1000 === 0 ? 's' : 'ms';
37+
fs.stat(file, (err, stat) => {
38+
/* istanbul ignore if */
39+
if (err) {
40+
return callback(err);
41+
}
3542

36-
// Cache the precision in a non-enumerable way
37-
Object.defineProperty(fs, cacheSymbol, { value: precision });
43+
const precision = stat.mtime.getTime() % 1000 === 0 ? 's' : 'ms';
44+
cachedPrecisions.set(dev, precision);
3845

39-
callback(null, stat.mtime, precision);
46+
callback(null, stat.mtime, precision);
47+
});
4048
});
4149
});
4250
}

0 commit comments

Comments
 (0)