last modified file date in node.js

node.js

node.js Problem Overview


I'm trying to retrieve the last modified date of a file on the server using node.js.

I've tried

file.lastModified;

and

file.lastModifiedDate;

both come back as undefined.

node.js Solutions


Solution 1 - node.js

You should use the stat function :

According to the documentation :

fs.stat(path, [callback])

> Asynchronous stat(2). The callback gets two arguments (err, stats) where stats is a fs.Stats object. It looks like this:

{ dev: 2049
, ino: 305352
, mode: 16877
, nlink: 12
, uid: 1000
, gid: 1000
, rdev: 0
, size: 4096
, blksize: 4096
, blocks: 8
, atime: '2009-06-29T11:11:55Z'
, mtime: '2009-06-29T11:11:40Z'
, ctime: '2009-06-29T11:11:40Z' 
}

As you can see, the mtime is the last modified time.

Solution 2 - node.js

For node v 4.0.0 and later:

fs.stat("/dir/file.txt", function(err, stats){
    var mtime = stats.mtime;
    console.log(mtime);
});

or synchronously:

var stats = fs.statSync("/dir/file.txt");
var mtime = stats.mtime;
console.log(mtime);

Solution 3 - node.js

Here you can get the file's last modified time in seconds.

fs.stat("filename.json", function(err, stats){
    let seconds = (new Date().getTime() - stats.mtime) / 1000;
    console.log(`File modified ${seconds} ago`);
});

Outputs something like "File modified 300.9 seconds ago"

Solution 4 - node.js

Just adding what Sandro said, if you want to perform the check as fast as possible without having to parse a date or anything, just get a timestamp in milliseconds (number), use mtimeMs.

Asynchronous example:

require('fs').stat('package.json', (err, stat) => console.log(stat.mtimeMs));

Synchronous:

console.log(require('fs').statSync('package.json').mtimeMs);

Solution 5 - node.js

With Async/Await:

const fs = require('fs').promises;
const lastModifiedDate = (await fs.stat(filePath)).mtime;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFredView Question on Stackoverflow
Solution 1 - node.jsSandro MundaView Answer on Stackoverflow
Solution 2 - node.jsOleg MikhailovView Answer on Stackoverflow
Solution 3 - node.jsjaggedsoftView Answer on Stackoverflow
Solution 4 - node.jscancerberoView Answer on Stackoverflow
Solution 5 - node.jsChristianView Answer on Stackoverflow