Reputation: 7083
I want to send to client filename and file created date, I tried to use fs.stat that provides birthtime but i dont see filename in there, SO my question, is birthtime is file created date ?
How can i send filename and date created as json ?
app.js
var readDirectory = require('./readDirectory');
app.get('/logs',function(req,res){
readDirectory.readDirectory(function(logFiles){
res.json(logFiles);
});
});
readDirectory.js
var fs = require('fs');
var path = './logs/ditLogs'
function readDirectory(callback){
fs.stat(path, function (err,stats) {
console.log('STATS',stats);
callback(stats);
});
}
exports.readDirectory = readDirectory;
Upvotes: 1
Views: 8581
Reputation: 699
The birthtime is the file creation datetime. This script shows the file creation date and filename as json.
const fs = require("fs");
fs.stat(
__filename,
function (err, stat) {
if (err) {
return console.log("err",err, stat);
} else {
console.log("stat", stat);
console.log( '{"createtime":"' + stat.birthtime.toISOString().replace(/[:\.T]/g,"-").replace(/[^0-9\-]*/g,"") +'","filename":"' + __filename + '"}' );
}
return;
}
);
Result:
Stats {
dev: 3767638129,
mode: 33206,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
blksize: 4096,
ino: 209135907696022600,
size: 379,
blocks: 0,
atimeMs: 1622023360041.0825,
mtimeMs: 1622023358411.5193,
ctimeMs: 1622023358411.5193,
birthtimeMs: 1621956288957.1938,
atime: 2021-05-26T10:02:40.041Z,
mtime: 2021-05-26T10:02:38.412Z,
ctime: 2021-05-26T10:02:38.412Z,
birthtime: 2021-05-25T15:24:48.957Z
}
{"createtime":"2021-05-25-15-24-48-957",
"filename":"D:\js\filecreatedatetest.js"}
The filename is the first parameter of fs.stat(), in your code this value is var path = './logs/ditLogs'
Upvotes: 0
Reputation: 838
If someone stumbles over this after all this time, as of Node v0.12.0 use this:
fs.stat(path, callback)
Where callback has two args err & stats. Stats object has property
birthtime
which is creation date.
Link to node api documentation https://nodejs.org/api/fs.html#fs_class_fs_stats
Upvotes: 5
Reputation: 838
Whether or not you can get the file creation time depends on the OS and file system. Traditional POSIX only defines ctime, which is (rather confusingly), the inode modification date, not the creation date, as other people have mentioned. However, on some operating systems, you can get st_birthtimespec, or st_birthtime which is a true "create" time. You'll need to check sys/stat.h on your host operating system to see what, if anything, is available.
Unfortunately, whether or not you can access the entire stat structure from node.js is a different kettle of fish. But at least you can figure out if your OS even supports it and go from there.
Upvotes: 2