hussain hussain - 3 months ago 9
Node.js Question

How to create object from two different fs methods?

I want to create object with filename and fileStat so in below code i am checking stats with async and for filename i used readDir now once i have values how can i create array of object ? I am trying to get filename and its created date and send it the client

objToReturn
. Any idea how can i acheive that task ?

app.js

function readDirectory(callback) {
var dirPath = './logs/ditLogs';
//this will get you list of all files. in directory
var files = fs.readdirSync(dirPath);
var objToReturn = [{
fileName: '',
fileStat: ''
}];
//then using async do like this
async.eachSeries(files, function(file, callback) {
var filePath = path.join(dirPath, file);
fs.stat(filePath, function(err, stats) {
objToReturn.fileStat = stats;
//write stats data into objToReturn
fs.readdir(path, function(err, items) {
objToReturn.filename = items;
});

callback();
});
}, function(err) {
//final callback when all files completed here send objToReturn to client
callback(objToReturn);
});

Answer

Okay, I think I see what you're trying to do here. You want to read all of the file paths in the given directory and then for each file, collect information before returning this information to a given callback. It appears right now that you are adding these props to the array objToReturn, instead of to each object and pushing it to objToReturn. In this way, you overwrite the properties on each async read.

You also use fs.readdir(path, function(err, items) { where I think you mean to refer to filePath that you declare earlier.

Try something like:

async.eachSeries(files, function(file, callback) {
    var filePath = path.join(dirPath, file);
    var fileInfo = {};
    fs.stat(filePath, function(err, stats) {
        fileInfo.fileStat = stats;
        //write stats data into objToReturn
        fs.readdir(filePath, function(err, items) {
            fileInfo.filename = items;
        });
        objToReturn.push(fileInfo);
        callback();
    });
}, function(err) {
Comments