2

我通过使用写了一个代码var fs= require("fs").promises;

  • 读取目录和子目录中的所有文件

var fs= require("fs").promises;

async function checkFileLoc(folderPath, depth) {
  depth -= 1;
  let files = await fs.readdir(folderPath);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stats = await fs.stat(filePath);
      if (stats.isDirectory() && depth > 0) {
        return checkFileLoc(filePath, depth);
      } else if (stats.isFile()) return filePath;
      else return null;
    })
  );
  return files
    .reduce((all, folderContents) => all.concat(folderContents), [])
    .filter((e) => e != null);
}

然后我fs-extra在我的项目中安装包并像这样替换var fs=require("fs");var fse=require("fs-extra");更改我的代码

var fse=require("fs-extra");

async function checkFileLoc(folderPath, depth) {
  depth -= 1;
  let files = await fse.readdir(folderPath);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stats = await fse.stat(filePath);
      if (stats.isDirectory() && depth > 0) {
        return checkFileLoc(filePath, depth);
      } else if (stats.isFile()) return filePath;
      else return null;
    })
  );
  return files
    .reduce((all, folderContents) => all.concat(folderContents), [])
    .filter((e) => e != null);
}

当我使用时,我fs得到了期望的输出,有人告诉我fs-extra是提前的fs,你所要做的就是用我的代码替换fsfse 的代码不能正常工作我犯了错误的任何解决方案?

  • 我使用时的输出var fs= require("fs").promise;是我读取目录中存在的所有文件
FilePath=
[/home/work/test/abc.html
/home/work/test/index.js
/home/work/test/product.js
]
  • var fse=require("fs-extra")使用空时我的输出
filePath=[]

我的输出在使用时没有出现fs-extra

4

1 回答 1

0

我试图弄清楚如果我正在使用我必须做出哪些改变var fse= require("fs-extra");

所以我的代码看起来像这样

var fse=require("fs-extra");

async function checkFileLoc(folderPath, depth) {
  depth -= 1;
  let files = fse.readdirSync(folderPath);
  files = await Promise.all(
    files.map(async (file) => {
      const filePath = path.join(folderPath, file);
      const stats = fse.statSync(filePath);
      if (stats.isDirectory() && depth > 0) {
        return checkFileLoc(filePath, depth);
      } else if (stats.isFile()) return filePath;
      else return null;
    })
  );
  return files
    .reduce((all, folderContents) => all.concat(folderContents), [])
    .filter((e) => e != null);
}

我更换了我的

  • var fs=require("fs");var fse=require("fs-extra");
  • let files = await fs.readdir(folderPath);let files = fs.readdirSync(folderPath);
  • const stats = await fs.stat(filePath);const stats = fs.statSync(filePath);

现在我得到了我的愿望输出

于 2021-05-27T16:01:00.270 回答