javascript - Nodejs path.resolve 未定义
问题描述
// 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 is not a function at fs.readdir (C:\backup\project\debug\codenotworking.js:17:24) at FSReqWrap.oncomplete (fs.js:139:20)
我在这里做错了什么?
解决方案
您通过在. _ 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);
}
}
}
推荐阅读
- ruby - 如何在 AWS Lambda 中正确加载 gem 扩展
- c++ - 将分配内存的前 16 个字节转换为 UDT
- asp.net - 强制从 https 重定向到 http .net core 2.1
- yocto - 何时修改 Poky 与创建新发行版
- c# - C#。如何为表单中的所有标签赋予相同的名称,所以如果一个对象与其中一个标签绑定,它将显示一些东西
- matlab - 为什么使用 myExcel.Workbooks.Open(filename) 会导致崩溃?
- apache - .htaccess 掩码原始网址
- python-3.x - 如何在 Apache Superset 中将 country_map 划分为多个国家/地区?
- linux - 脚本只处理输入文件的第一行
- javascript - 使用 Javascript + Jquery 将来自 firebase 的数据显示到刷新的 html 表中