首页 > 解决方案 > 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)

我在这里做错了什么?

标签: javascriptnode.js

解决方案


通过在. _ path_ 将参数名称更改为其他名称。pathcollectFileNamesRecursively

除此之外,以这种方式使用带有回调的递归是行不通的——我建议使用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);
        }
    }

}

推荐阅读