hussain hussain - 3 months ago 12
Node.js Question

how to check stats for multiple file in directory and send as json to client?

Lets assume i have three files in directory i want to check stats for all these files and send birthtimes to client ,Its always returning one file stats as you can see in data. How can i get stats for all files from directory ?

app.js

var path = './logs/ditLogs'
fs.stat(path, function (err,stats) {
console.log('STATS',stats);
fileData.birthtime = stats.birthtime;
//callback(stats.mtime);
});


data

{ birthtime: Tue Jul 12 2016 09:33:14 GMT-0400 (Eastern Daylight Time),
filename: ['server.log', 'server1.log' ] }

Answer

Async library is the way to go. http://caolan.github.io/async/docs.html

I would suggest something like this

var dirPath = './logs/ditLogs'; //this will get you list of all files. in directory var files = fs.readdirSync(dirPath); var objToReturn = {}; //then using async do like this async.eachSeries(files, function (file, callback) { var filePath = path.join(dirPath, file); fs.stat(filePath, function(err, stats){ //write stats data into objToReturn callback(); }); }, function(err){ //final callback when all files completed here send objToReturn to client });

Hope this helps.