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' },
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.
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 aDate
object from that?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 usingfs.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 thepath.basename()
method: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.