Sus*_*ush 5 jquery json node.js
var getfiles = function (context) {
var scriptPath = '/var/names/myfolder';
fs.readdir(scriptPath, function (err, files) {
if (err) return context.sendJson(err, 404);
var resultingJson = {};
for (var j = 0; j < files.length; j++) {
subfolder = scriptPath + files[j];
console.log(files[j]);// prints art,creation
fs.readdir(subfolder, function (err, fi) {
//fi prints [artdetails.txt,artinfo.txt]
// [creationdetails.txt,create.txt]
// console.log(files[j]);// prints undefined here
resultingJson[files[j]] = fi;
});
}
console.log(resultingJson); // returing {}
context.sendJson(resultingJson, 200);
});
}
Run Code Online (Sandbox Code Playgroud)
上面的代码用于获取子文件夹myfolder中的文件,它包含art,creation并在此art文件夹中包含文件artdetails.txt,artinfo.txt创建文件夹包含文件creationdetails.txt,create.txt等.
文件夹和文件成功获取,但我想生成这样的JSON格式:
{`art':['artdetails',artinfo],'creation':['creationdetails','create']} format
Run Code Online (Sandbox Code Playgroud)
怎么可能?
我用, resultingJson[files[j]] = fi;但它返回{}.
我的代码出了什么问题?
这里有一些问题。readdir首先也是最重要的,Felix Kling 对异步做出了正确的观察,更具体地说是指readdirfor 循环的内部。您所看到的部分内容是,您的 console.log 和 JSON 响应是在目录完成读取之前发生的。此外,可能发生的情况是正在丢失上下文j,很可能最终会出现最后一个值。
像async这样的控制流库可能会有所帮助,例如every方法。
var fs = require('fs'),
async = require('async');
var scriptPath = '/var/names/myfolder';
var getfiles = function(context) {
// Read contents of the parent directory
fs.readdir(scriptPath, function(err, files) {
if (err) return context.sendJson(err, 404);
var result = {};
// Asynchronously iterate over the directories
async.each(files, function iterator(directory, next){
var subfolder = scriptPath + directory;
// Read contents of the child directory
fs.readdir(subfolder, function(err, file){
if (err) return next(err);
// Set the property
result[directory] = file;
// Now that we've finished reading these contents,
// lets read the contents of the next child folder
next();
// When there are none left, the `complete` callback will
// be reached and then it is safe to return a JSON string
});
}, function complete(err){
// All children directories have been read
// and the `result` object should be what we expect
if (err) return context.sendJson(err, 404);
context.sendJson(result, 200);
});
});
};
Run Code Online (Sandbox Code Playgroud)
我已经通过模拟您的文件夹/文件结构对此进行了测试,它似乎工作正常。它生成以下 JSON 字符串:
{"art":["artdetails.txt","artinfo.txt"],"creation":["create.txt","creationdetails.txt"]}
Run Code Online (Sandbox Code Playgroud)
迭代器是并行调用的,因此顺序可能会改变,但不会产生影响。
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |