[英]How to recursively read file in a tree like directory structure in node js
I have a root directory say "A" inside this directory i am having lots of directories say "1","2","3","4","5"........ and in all these subdirectories i have single file called cucumber.json. 我在此目录中有一个根目录,说“ A”,我有很多目录,说“ 1”,“ 2”,“ 3”,“ 4”,“ 5” ........等等子目录中,我有一个名为cucumber.json的文件。 All i want to do is read the cucumber.json file and get the accumulated result. 我要做的就是读取cumulage.json文件并获得累积结果。 How can i achieve this using node js. 我如何使用节点js实现此目的。
In the below screen shot my root directory is "cucumber" and inside that i have lot of sub directories. 在下面的屏幕快照中,我的根目录是“黄瓜”,在其中,我有很多子目录。 All these sub directories contains a single file named cucumber.json. 所有这些子目录都包含一个名为Cucumber.json的文件。
Are there any dedicated node package which can make my work easy. 是否有任何专用的节点软件包可以简化我的工作。 Let me know if any further info is required. 让我知道是否需要其他信息。
Hi there please try the following (javascript): 嗨,请尝试以下操作(javascript):
// Require filesystem package for IO operations
var fs = require('fs');
// Put the path you are looking for here
var path = "d:\\nodef";
//Call the function defined below
recursiveloop(path, function(err,result){
/* begin processing of each result */
// For each file in the array
for(i=0;i<result.length;i++)
{
//Write the name of the file
console.log('Processing: ' + result[i]);
//Read the file
fs.readFile(result[i], 'utf8', function(err, data){
//If there is an error notify to the console
if(err) console.log('Error: ' + err);
//Parse the json object
var obj = JSON.parse(data);
//Print out contents
console.log('Name: ' + obj.name);
console.log('Position: ' + obj.position);
})
}
});
// Asynchronous function to read folders and files recursively
function recursiveloop(dir, done)
{
var results = [];
fs.readdir(dir, function(err, list){
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = dir + '/' + file;
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
recursiveloop(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.