我想编写一个脚本来检查给定路径的子目录和文件。问题是:当一个子目录有多个子目录时就会出错。如果没有多个子目录,则不会出现错误。有人知道我的代码失败的原因吗?
感谢您的帮助!
此:
const fs = require('fs');
class File
{
constructor(fileName, directory)
{
this.fileName = fileName;
this.directory = directory;
}
read()
{
return fs.readFileSync(this.directory.formatedPath(this.fileName), 'utf8', function(err, data)
{
if (err) throw err;
return data.toString();
});
}
write()
{
}
}
class Directory
{
constructor(path, pathLevel = 0)
{
this.reveal(path, pathLevel);
this.organizeMembers();
}
reveal(path, pathLevel)
{
this.path = path;
this.pathLevel = pathLevel;
this.directory = fs.readdirSync(this.path);
}
organizeMembers()
{
this.files = [], this.directories = [];
for (var member of this.directory)
{
if (fs.lstatSync(member).isFile()) this.files.push(new File(member, this));
if (fs.lstatSync(member).isDirectory())
{
this.directories.push(new Directory(this.formatedPath(member), this.pathLevel+1));
}
}
}
formatedPath(member)
{
if (this.path[this.path.length -1] !== '/') return this.path + '/' + member;
return this.path + member;
}
createDirectory(path)
{
if (!fs.existsSync(path)) fs.mkdirSync(path);
}
}
var x = new Directory('./');
console.log(x);
产生这个:
fs.js:958
binding.lstat(pathModule.toNamespacedPath(path));
^
Error: ENOENT: no such file or directory, lstat 'Neuer Ordner 3'
at Object.fs.lstatSync (fs.js:958:11)
at Directory.organizeMembers (/Users/mrb/Desktop/testFolder/nodePlayground.js:49:14)
at new Directory (/Users/mrb/Desktop/testFolder/nodePlayground.js:32:10)
at Directory.organizeMembers (/Users/mrb/Desktop/testFolder/nodePlayground.js:52:31)
at new Directory (/Users/mrb/Desktop/testFolder/nodePlayground.js:32:10)
at Object.<anonymous> (/Users/mrb/Desktop/testFolder/nodePlayground.js:70:9)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
但为什么?
答案 0 :(得分:0)
您的问题是readdirSync
未输出完整路径。因此,当您重新列出子目录文件并使用lstatSync
时,您错过了子目录路径,这就是您收到错误的原因:ENOENT: no such file or directory, lstat 'Neuer Ordner 3'
,因为该文件不存在。
您所要做的就是使用path.join
const path = require('path');
/* ... */
organizeMembers() {
this.files = [], this.directories = [];
for (var member of this.directory) {
const filepath = path.join(this.path, member);
// No need to use fs.lstat twice.
const stat = fs.lstatSync(filepath);
if (stat.isFile())
this.files.push(new File(member, this));
else if (stat.isDirectory())
this.directories.push(new Directory(filepath, this.pathLevel + 1));
}
}
您的formatedPath
功能可以移除,以支持path.join
。