Kar*_*bit 2 javascript node.js
// 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"));
Run Code Online (Sandbox Code Playgroud)
我正在使用 nodejs v10.8.0 并且目录结构是
- project/
- debug/
- codenotworking.js
- public/
- js/
- file2.js
- file.html
Run Code Online (Sandbox Code Playgroud)
每当我运行此代码时,我都会收到以下错误
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通过specifing进口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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2220 次 |
| 最近记录: |