[英]Nodejs path.resolve is not defined
// codenotworking
const path = require("path");
const fs = require("fs");
log = console.log;
const names = [];
function collectFileNamesRecursively(path) {
fs.readdir(path, (err, files) => {
err ? log(err) : log(files);
// replacing paths
for (const index in files) {
const file = files[index];
files[index] = path.resolve(path, file);
}
for (let file of files) {
fs.stat(file, (err, stat) => {
err ? log(err) : null;
if (stat.isDirectory()) {
collectFileNamesRecursively(file);
}
names.push(file);
});
}
});
}
collectFileNamesRecursively(path.join(__dirname, "../public"));
i am using nodejs v10.8.0 and the directory stucture is我正在使用nodejs v10.8.0,目录结构是
- project/
- debug/
- codenotworking.js
- public/
- js/
- file2.js
- file.html
whenever i run this code i get the following error每当我运行此代码时,我都会收到以下错误
TypeError: path.resolve is not a function at fs.readdir (C:\backup\project\debug\codenotworking.js:17:24) at FSReqWrap.oncomplete (fs.js:139:20) TypeError: path.resolve is not a function at fs.readdir (C:\backup\project\debug\codenotworking.js:17:24) at FSReqWrap.oncomplete (fs.js:139:20)
what am i doing wrong here?我在这里做错了什么?
You're shadowing your path
import by specifing the path
parameter in collectFileNamesRecursively
.您通过在collectFileNamesRecursively
中指定path
参数来隐藏path
导入。 Change the parameter name to something else.将参数名称更改为其他名称。
Apart from that using recursion with callbacks this way won't work - I would recommend using async/await
.除此之外,以这种方式使用带有回调的递归是行不通的——我建议使用async/await
。 Something like:就像是:
const path = require('path');
const fs = require('fs');
async function collectFileNamesRecursively(currBasePath, foundFileNames) {
const dirContents = await fs.promises.readdir(currBasePath);
for (const file of dirContents) {
const currFilePath = path.resolve(currBasePath, file);
const stat = await fs.promises.stat(currFilePath);
if (stat.isDirectory()) {
await collectFileNamesRecursively(currFilePath, foundFileNames);
} else {
foundFileNames.push(file);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.