【发布时间】:2020-04-22 23:23:06
【问题描述】:
我正在创建一个程序...
1. 检测任何给定系统上的所有驱动器。
2. 扫描这些驱动器以查找特定文件类型的文件。例如,
它可能会在所有驱动器中搜索任何 jpeg、png 和 svg 文件。
3. 然后将结果以以下所需格式存储在 JSON 文件中。
{
"C:": {
"jpeg": [
...
{
"path": "C:\\Users\\John\\Pictures\\example.jpeg",
"name": "example",
"type": "jpeg",
"size": 86016
},
...
],
"png": [],
"svg": []
},
...
}
代码...
async function scan(path, exts) {
try {
const stats = await fsp.stat(path)
if (stats.isDirectory()) {
const
childPaths = await fsp.readdir(path),
promises = childPaths.map(
childPath => scan(join(path, childPath), exts)
),
results = await Promise.all(promises)
// Likely needs to change.
return [].concat(...results)
} else if (stats.isFile()) {
const fileExt = extname(path).replace('.', '')
if (exts.includes(fileExt)){
// Likely needs to change.
return {
"path": path,
"name": basename(path, fileExt).slice(0, -1),
"type": fileExt,
"size": stats.size
}
}
}
return []
}
catch (error) {
return []
}
}
const results = await Promise.all(
config.drives.map(drive => scan(drive, exts))
)
console.log(results) // [ Array(140), Array(0), ... ]
// And I would like to do something like the following...
for (const drive of results) {
const
root = parse(path).root,
fileExt = extname(path).replace('.', '')
data[root][fileExt] = []
}
await fsp.writeFile('./data.json', JSON.stringify(config, null, 2))
全局results 当然被划分为与每个驱动器对应的单独数组。但目前它将所有对象组合成一个巨大的数组,尽管它们有相应的文件类型。我目前也无法知道每个驱动器属于哪个数组,尤其是如果驱动器的数组不包含任何我可以解析以检索根目录的项目。
我显然可以map 或再次循环通过全局results,然后将所有内容整理出来,如下图所示,但是让scan() 从一开始就处理所有事情会更干净。
// Initiate scan sequence.
async function initiateScan(exts) {
let
[config, data] = await Promise.all([
readJson('./config.json'),
readJson('./data.json')
]),
results = await Promise.all(
// config.drives.map(drive => scan(drive, exts))
['K:', 'D:'].map(drive => scan(drive, exts))
)
for (const drive of results) {
let root = false
for (const [i, file] of drive.entries()) {
if (!root) root = parse(file.path).root.slice(0,-1)
if (!data[root][file.type] || !i) data[root][file.type] = []
data[root][file.type].push(file)
}
}
await fsp.writeFile('./data.json', JSON.stringify(config, null, 2))
}
由于我对异步和一般对象缺乏经验,我不太确定如何最好地处理map( ... )/scan 中的数据。我什至不确定如何最好地构造scan() 的输出,以便全局results 的结构易于操作。
任何帮助将不胜感激。
【问题讨论】:
-
“然后将结果存储在具有以下格式的 JSON 文件中......”。您的意思是结果应该以这种方式存储吗?
-
@Roamer-1888 是的,这就是我的意思。这就是我想存储它们的方式
标签: javascript node.js asynchronous promise fs