[我正在尝试在NodeJS中构建一个函数,该函数使用fs
库递归检查它是文件还是目录,从而无限深入子目录,我的代码是这样的:
function generateComponents(path) {
fs.readdirSync(path).forEach((file) => {
if(fs.existsSync(file) && fs.lstatSync(file).isDirectory()) {
generateComponents(path+'/'+file);
}
else {
//Do some code
}
});
}
它适用于第一个文件夹/目录,但是当它适用于下一个目录时,它接受为文件,并且条件进入其他部分。我做错什么了吗?
一个问题是代码中的file
只是文件名。要递归,您必须将文件名与路径重新组合,以便在与原始路径不同的目录中调用generateComponents。这包括当您调用fs.existsSync()
和fs.lstatSync()
时:
const path = require('path');
function generateComponents(dir) {
fs.readdirSync(path).forEach((file) => {
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
generateComponents(fullPath);
}
else {
//Do some code
}
});
}
FYI,您还应该对withFileTypes
使用fs.readdirSync()
选项,因为这样可以节省fs.lstatSync()
调用,而完全不需要fs.existsSync()
调用。 fs.readdirSync()
只是告诉您文件在那里,您不必检查文件是否再次在那里。
使用withFileTypes
的简化版本如下:
const path = require('path');
function generateComponents(dir) {
fs.readdirSync(path, {withFileTypes: true}).forEach((entry) => {
let fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
console.log(`directory: ${fullPath}`)
generateComponents(fullPath);
}
else if (entry.isFile()) {
//Do some code with fullPath file
console.log(`filename: ${fullPath}`)
} else {
// apparently there are some other things that could be here
// perhaps unlikely, but this is defensive coding
console.log(`unexpected type: ${fullPath}`);
}
});
}