我想创建带有filename和fileStat的对象,所以在下面的代码中我正在检查带有异步和文件名的统计数据我现在使用readDir一旦我有值我怎样才能创建对象数组?我正在尝试获取文件名及其创建日期,并将其发送给客户端objToReturn
。任何想法我怎么能实现这个任务?
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);
});
答案 0 :(得分:1)
好的,我想我知道你在这里要做什么。您希望读取给定目录中的所有文件路径,然后针对每个文件,在将此信息返回给定回调之前收集信息。现在看来,您要将这些道具添加到数组objToReturn
,而不是添加到每个对象并将其推送到objToReturn
。通过这种方式,您可以覆盖每个异步读取的属性。
您还可以使用fs.readdir(path, function(err, items) {
我认为您的意思是指您之前声明的filePath
。
尝试类似:
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) {
答案 1 :(得分:0)
你可以试试这个:
function readDirectory(callback) {
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) {
objToReturn.fileStat = stats;
//write stats data into objToReturn
fs.readdir(path, function(err, items) {
objToReturn.filename = items;
objToReturn.push({
fileName: items,
fileStat: stats
})
});
callback();
});
}, function(err) {
//final callback when all files completed here send objToReturn to client
callback(objToReturn);
});
}
希望这应该有用。