utimes.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var fs = require('graceful-fs')
  2. var path = require('path')
  3. var os = require('os')
  4. // HFS, ext{2,3}, FAT do not, Node.js v0.10 does not
  5. function hasMillisResSync () {
  6. var tmpfile = path.join('millis-test-sync' + Date.now().toString() + Math.random().toString().slice(2))
  7. tmpfile = path.join(os.tmpdir(), tmpfile)
  8. // 550 millis past UNIX epoch
  9. var d = new Date(1435410243862)
  10. fs.writeFileSync(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141')
  11. var fd = fs.openSync(tmpfile, 'r+')
  12. fs.futimesSync(fd, d, d)
  13. fs.closeSync(fd)
  14. return fs.statSync(tmpfile).mtime > 1435410243000
  15. }
  16. function hasMillisRes (callback) {
  17. var tmpfile = path.join('millis-test' + Date.now().toString() + Math.random().toString().slice(2))
  18. tmpfile = path.join(os.tmpdir(), tmpfile)
  19. // 550 millis past UNIX epoch
  20. var d = new Date(1435410243862)
  21. fs.writeFile(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141', function (err) {
  22. if (err) return callback(err)
  23. fs.open(tmpfile, 'r+', function (err, fd) {
  24. if (err) return callback(err)
  25. fs.futimes(fd, d, d, function (err) {
  26. if (err) return callback(err)
  27. fs.close(fd, function (err) {
  28. if (err) return callback(err)
  29. fs.stat(tmpfile, function (err, stats) {
  30. if (err) return callback(err)
  31. callback(null, stats.mtime > 1435410243000)
  32. })
  33. })
  34. })
  35. })
  36. })
  37. }
  38. function timeRemoveMillis (timestamp) {
  39. if (typeof timestamp === 'number') {
  40. return Math.floor(timestamp / 1000) * 1000
  41. } else if (timestamp instanceof Date) {
  42. return new Date(Math.floor(timestamp.getTime() / 1000) * 1000)
  43. } else {
  44. throw new Error('fs-extra: timeRemoveMillis() unknown parameter type')
  45. }
  46. }
  47. function utimesMillis (path, atime, mtime, callback) {
  48. // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
  49. fs.open(path, 'r+', function (err, fd) {
  50. if (err) return callback(err)
  51. fs.futimes(fd, atime, mtime, function (err) {
  52. if (err) return callback(err)
  53. fs.close(fd, callback)
  54. })
  55. })
  56. }
  57. module.exports = {
  58. hasMillisRes: hasMillisRes,
  59. hasMillisResSync: hasMillisResSync,
  60. timeRemoveMillis: timeRemoveMillis,
  61. utimesMillis: utimesMillis
  62. }