NodeJS Snippet – File Access/Modification Stat And Utimes One-Second Scope

You might get a high-precision (milliseconds) from the file-stat,
but you have to use a lower-resolution value, for utimes.

It is got to do with internal-linking to the operation-system’s libs..

but here is a nice working example for you to play-with,
essentially just reading a file’s content and last-modification/last-access times,
and rewrite the file (delete/write new one) with some altered-content,
but restoring the timestamp of the original file.

for this example to work just place a text file named file.txt, with any content, and any timestamp (you can set timestamp manually using variety of programs..), and see that the file with the new content is keeping its timestamp after-all.

/* Working With NodeJS' `utimes` and `stat`.*/
var fs      = require('fs')
   ,path    = require('path')
   ,file    = path.resolve('./file.txt')     //will work on every OS (even though it is a "Unix-slash").
   ,stat    = fs.lstatSync(file)             //preform any action on symbolic-link itself. (for example unlink, to delete a symbolic-link without following it to delete the actual file)
 //,stat    = fs.statSync(file)              //follow symbolic-link to where it points, file might be placed in another folder!
   ,content
   ;

content = fs.readFileSync(file, {encoding: "utf8"});
content = content.replace(/foo/g, "bar") + "\nSome Junk...";

fs.unlinkSync(file);
fs.writeFileSync(file, content, {encoding: "utf8"});

fs.utimesSync(file, stat.atime.getTime()/1000, stat.mtime.getTime()/1000); //will restore the access/modification time of the original-file.

/*
.atime                access time
.mtime                modification time
.birthtime || .ctime  creation time     */

You can read about this issue on:
https://github.com/nodejs/node/issues/2069#issuecomment-294596104.