如何使用fs模块获取文件创建日期? [英] How to get file created date using fs module?
问题描述
我有linux服务器,其中有使用winston旋转创建的日志文件,因此filename
具有文件名和创建日期,因此您可以看到在2017-04-14
上创建的data
server20170414181405.log
中的第一个文件,但使用fs.stats.birthtime
其给定的fileDate Apr-19-2017
.如何在Linux上获得准确的文件创建日期?
I have linux server where i have logs file that are being created with winston rotation , so filename
has filename and created date, so you can see first file in data
server20170414181405.log
created on 2017-04-14
but using fs.stats.birthtime
its giving fileDate Apr-19-2017
. How can i get accurate file created date working on linux ?
cron.js
fs.stat(filePath, function (err, stats) {
if (err) return cb2(err);
var fileInfo = { fileDate: stats.birthtime, filename: file };
console.log(fileInfo);
});
数据
{ fileDate: Wed Apr 19 2017 00:51:56 GMT-0400 (EDT),
filename: 'server20170414181405.log' },
{ fileDate: Wed Apr 19 2017 00:52:04 GMT-0400 (EDT),
filename: 'server20170414212655.log' },
{ fileDate: Wed Apr 19 2017 00:52:07 GMT-0400 (EDT),
filename: 'server20170415023845.log' },
推荐答案
获取真实文件创建时间非常困难. linux内核只是最近才开始支持它,所以我不知道birthtime
值的准确性如何.这可能取决于您使用的linux版本.这篇文章有一些背景:
Getting the real file creation time has been difficult. The linux kernel only recently started supporting it, so I don't know how accurate the birthtime
value is going to be. It may depend on the version of linux you are using. There is some background in this post:
但是,您正在将创建时间添加到文件名中.为什么不使用fs.stat()
而不是仅解析文件名并从中创建一个Date
对象呢?
However, you are adding the creation time to the file name. Instead of using fs.stat()
, why not just parse the file name and create a Date
object from that?
const filename = 'server20170414181405.log';
const dateString = filename.substr(6, 4) + '-' + filename.substr(10, 2)
+ '-' + filename.substr(12, 2) + 'T' + filename.substr(14, 2)
+ ':' + filename.substr(16, 2) + ':' + filename.substr(18, 2);
// '2017-04-14T18:14:05'
const createDate = new Date(dateString);
对于文件名中使用的任何时区,您都可以将Z
添加到UTC的末尾或正确的时区偏移量.当然,这是假设您的文件名是正确的,但是,如果这样,它看起来比使用fs.stat()
更容易,更快.
You can either add Z
to the end for UTC or the correct timezone offset, for whatever timezone you are using in the filename. Of course, this assumes that your filenames are accurate, but, if so, it seems easier, and faster, than using fs.stat()
.
-编辑-
您似乎已经在filePath
变量中有了文件的路径,因此可以使用path.basename()
方法获取文件名:
It looks like you already have the path to the file in the filePath
variable, so you can get the file name using the path.basename()
method:
const path = require('path');
const filename = path.basename(filePath);
在此处查看节点"文档: https://nodejs.org/dist/latest-v6.x/docs/api/path.html#path_path_basename_path_ext .一旦有了文件名,就可以使用我原始帖子中的代码来获取日期.
See the Node docs here: https://nodejs.org/dist/latest-v6.x/docs/api/path.html#path_path_basename_path_ext. Once you have the file name, you can use the code in my original post to get the date.
这篇关于如何使用fs模块获取文件创建日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!