【发布时间】:2021-08-15 11:52:04
【问题描述】:
我用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 而你所要做的就是用fse 替换fs
我的代码无法正常工作我犯了错误的任何解决方案?
- 我在使用
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时我的输出没有出现
【问题讨论】:
-
“有人告诉我 fs-extra 是先进的” - 那么问那个人?我完全不明白你为什么要使用 fs-extra - 你有一个使用原生 fs 的正常工作代码,为什么要使用额外的库?
-
因为在项目中所有内容都写在
fs-extra这就是为什么需要更改@Bergi -
好吧,但是代码“无法正常工作”到底是怎么回事?
-
究竟出了什么问题?错误信息?请提供示例输入和错误输出以及预期输出...等。
-
@derpirscher 显然(已删除 cmets)他们的团队负责人要求他们使用它,以便在整个项目中保持一致。
标签: javascript node.js promise fs fs-extra