node.js 中的最后修改文件日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7559555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:37:10  来源:igfitidea点击:

last modified file date in node.js

node.js

提问by Fred

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

我正在尝试使用 node.js 检索服务器上文件的最后修改日期。

I've tried

我试过了

file.lastModified;

and

file.lastModifiedDate;

both come back as undefined.

两者都返回未定义。

采纳答案by Oleg Mikhailov

For node v 4.0.0 and later:

对于节点 v 4.0.0 及更高版本:

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);

回答by Sandro Munda

You should use the stat function :

您应该使用 stat 函数:

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:

异步统计(2)。回调有两个参数 (err, stats),其中 stats 是一个 fs.Stats 对象。它看起来像这样:

{ 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 mtimeis the last modified time.

如您所见,这mtime是最后修改时间。

回答by jaggedsoft

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"

输出类似“文件在 300.9 秒前修改”之类的内容

回答by cancerbero

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

只需添加 Sandro 所说的内容,如果您想在无需解析日期或任何内容的情况尽快执行检查,只需获取以毫秒为单位的时间戳(数字),请使用mtimeMs. 同步示例:

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

Synchronous:

同步:

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