gpt4 book ai didi

javascript - Nodejs path.resolve 未定义

转载 作者:行者123 更新时间:2023-12-05 00:34:40 25 4
gpt4 key购买 nike

// 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"));

我正在使用nodejs v10.8.0,目录结构是
 - project/
- debug/
- codenotworking.js
- public/
- js/
- file2.js
- file.html

每当我运行此代码时,我都会收到以下错误

TypeError:path.resolve 不是函数
在 fs.readdir (C:\backup\project\debug\codenotworking.js:17:24)
在 FSReqWrap.oncomplete (fs.js:139:20)

我在这里做错了什么?

最佳答案

你是 shadowing您的 path通过指定 path 导入collectFileNamesRecursively 中的参数.将参数名称更改为其他名称。

除此之外,以这种方式使用带有回调的递归是行不通的——我建议使用 async/await .就像是:

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);
}
}

}

关于javascript - Nodejs path.resolve 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61977213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com