我对node.js中的这段代码有一个问题。我想递归地遍历目录树,并将回调action
应用于树中的每个文件。这是我目前的代码:
var fs = require("fs");
// General function
var dive = function (dir, action) {
// Assert that it's a function
if (typeof action !== "function")
action = function (error, file) { };
// Read the directory
fs.readdir(dir, function (err, list) {
// Return the error if something went wrong
if (err)
return action(err);
// For every file in the list
list.forEach(function (file) {
// Full path of that file
path = dir + "/" + file;
// Get the file's stats
fs.stat(path, function (err, stat) {
console.log(stat);
// If the file is a directory
if (stat && stat.isDirectory())
// Dive into the directory
dive(path, action);
else
// Call the action
action(null, path);
});
});
});
};
问题是,在for each循环中,通过变量path
为每个文件调用stat。当回调被调用时,path
已经有了另一个值,因此它将dive
%s放到错误的目录中,或者为错误的文件调用action
。
也许这个问题可以通过使用fs.statSync
很容易地解决,但这不是我喜欢的解决方案,因为它阻塞了进程。
发布于 2011-08-12 22:58:31
var path = dir + "/" + file;
您忘记了将path
设置为局部变量。现在它不会在你背后的循环中被改变。
发布于 2014-05-14 22:43:13
为此,请使用node-dir。因为您需要对目录和文件执行单独的操作,所以我将使用node-dir提供两个简单的迭代器。
异步迭代目录及其子目录的文件,并将文件路径数组传递给回调。
var dir = require('node-dir');
dir.files(__dirname, function(err, files) {
if (err) throw err;
console.log(files);
//we have an array of files now, so now we'll iterate that array
files.forEach(function(filepath) {
actionOnFile(null, filepath);
})
});
异步迭代目录的子目录及其子目录,并将目录路径数组传递给回调。
var dir = require('node-dir');
dir.subdirs(__dirname, function(err, subdirs) {
if (err) throw err;
console.log(subdirs);
//we have an array of subdirs now, so now we'll iterate that array
subdirs.forEach(function(filepath) {
actionOnDir(null, filepath);
})
});
发布于 2020-02-07 05:16:45
这里有一个NPM模块:
npm dree
示例:
const dree = require('dree');
const options = {
depth: 5, // To stop after 5 directory levels
exclude: /dir_to_exclude/, // To exclude some pahts with a regexp
extensions: [ 'txt', 'jpg' ] // To include only some extensions
};
const fileCallback = function (file) {
action(file.path);
};
let tree;
// Doing it synchronously
tree = dree.scan('./dir', options, fileCallback);
// Doing it asynchronously (returns promise)
tree = await dree.scanAsync('./dir', options, fileCallback);
// Here tree contains an object representing the whole directory tree (filtered with options)
https://stackoverflow.com/questions/7041638
复制相似问题