Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two fileStat.mtime in nodejs?

Tags:

date

node.js

See the code:

var fs = require('fs');

var file = "e:/myfile.txt";

fs.stat(file, function(err, stat1) {
  console.log(stat1.mtime);
  fs.stat(file, function(err, stat2) {
    console.log(stat2.mtime);
    console.log(stat1.mtime == stat2.mtime);
    console.log(stat1.mtime === stat2.mtime);
  });
});

And the result:

Sun, 20 May 2012 15:47:15 GMT
Sun, 20 May 2012 15:47:15 GMT
false
false

I didn't change the file during execution. But you can see no matter == or ===, they are not equal.

How to compare two mtime in nodejs?

like image 269
Freewind Avatar asked May 20 '12 16:05

Freewind


2 Answers

Use date.getTime() to compare:

function datesEqual(a, b) {
    return a.getTime() === b.getTime();
}
like image 110
Freewind Avatar answered Nov 17 '22 14:11

Freewind


== on objects test if the objects are equal. However, < and > do the job propertly for Date objects, so you can simply use this function to compare the two objects:

function datesEqual(a, b) {
    return !(a > b || b > a);
}
like image 6
ThiefMaster Avatar answered Nov 17 '22 15:11

ThiefMaster