mtime-precision.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const cacheSymbol = Symbol();
  3. function probe(file, fs, callback) {
  4. const cachedPrecision = fs[cacheSymbol];
  5. if (cachedPrecision) {
  6. return fs.stat(file, (err, stat) => {
  7. /* istanbul ignore if */
  8. if (err) {
  9. return callback(err);
  10. }
  11. callback(null, stat.mtime, cachedPrecision);
  12. });
  13. }
  14. // Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
  15. const mtime = new Date((Math.ceil(Date.now() / 1000) * 1000) + 5);
  16. fs.utimes(file, mtime, mtime, (err) => {
  17. /* istanbul ignore if */
  18. if (err) {
  19. return callback(err);
  20. }
  21. fs.stat(file, (err, stat) => {
  22. /* istanbul ignore if */
  23. if (err) {
  24. return callback(err);
  25. }
  26. const precision = stat.mtime.getTime() % 1000 === 0 ? 's' : 'ms';
  27. // Cache the precision in a non-enumerable way
  28. Object.defineProperty(fs, cacheSymbol, { value: precision });
  29. callback(null, stat.mtime, precision);
  30. });
  31. });
  32. }
  33. function getMtime(precision) {
  34. let now = Date.now();
  35. if (precision === 's') {
  36. now = Math.ceil(now / 1000) * 1000;
  37. }
  38. return new Date(now);
  39. }
  40. module.exports.probe = probe;
  41. module.exports.getMtime = getMtime;