How to get file created date using fs module?

一笑奈何 提交于 2019-12-13 06:52:01

问题


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

data

  { 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' },

回答1:


The stat.birthtime is the real date of file creation in server timezone. Probably the difference happens because Winston and your server are working in different timezones.

If is not the case to align both timezones, and you need of the stat.birthtime in some specific timezone, you can use moment-timezone date constructor.




回答2:


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:

https://unix.stackexchange.com/questions/304779/is-there-still-no-linux-kernel-interface-to-get-file-creation-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);

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().

-- EDIT --

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

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.



来源:https://stackoverflow.com/questions/43592299/how-to-get-file-created-date-using-fs-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!