我想编写一个检查给定路径的子目录和文件的脚本。问题是:当一个子目录具有多个子目录时,将出现错误。如果没有多个子目录,则不会出现错误。有人知道我的代码为什么会失败吗?
谢谢您的帮助 !
这个:
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)
但为什么 ?
最佳答案
您的问题是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
。关于javascript - Node js:识别目录成员类型时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49908154/