Skip to content

Commit

Permalink
feat: cache precision per device
Browse files Browse the repository at this point in the history
See #103
  • Loading branch information
julien-f committed May 10, 2021
1 parent 9f8c303 commit 3edb1c3
Showing 1 changed file with 27 additions and 19 deletions.
46 changes: 27 additions & 19 deletions lib/mtime-precision.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,48 @@
const cacheSymbol = Symbol();

function probe(file, fs, callback) {
const cachedPrecision = fs[cacheSymbol];
let cachedPrecisions = fs[cacheSymbol];
if (cachedPrecisions === undefined) {
cachedPrecisions = new Map();

if (cachedPrecision) {
return fs.stat(file, (err, stat) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

callback(null, stat.mtime, cachedPrecision);
});
// Cache the precisions in a non-enumerable way
Object.defineProperty(fs, cacheSymbol, { value: cachedPrecisions });
}

// Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
const mtime = new Date((Math.ceil(Date.now() / 1000) * 1000) + 5);

fs.utimes(file, mtime, mtime, (err) => {
return fs.stat(file, (err, stat) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

fs.stat(file, (err, stat) => {
const dev = stat.dev;

// Precisions are cached by device, see #103
const precision = cachedPrecisions[dev];
if (precision !== undefined) {
return callback(null, stat.mtime, precision);
}

// Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
const mtime = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);

fs.utimes(file, mtime, mtime, (err) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

const precision = stat.mtime.getTime() % 1000 === 0 ? 's' : 'ms';
fs.stat(file, (err, stat) => {
/* istanbul ignore if */
if (err) {
return callback(err);
}

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

callback(null, stat.mtime, precision);
callback(null, stat.mtime, precision);
});
});
});
}
Expand Down

0 comments on commit 3edb1c3

Please sign in to comment.