【发布时间】:2020-04-21 17:16:46
【问题描述】:
应该注意的是,我对所有这些异步的东西都很陌生。
我试图等到文件的存在得到验证,如果需要,脚本会在更新文件之前创建文件。但是,我似乎无法弄清楚该怎么做。
我知道我可以使用fs.writeFileSync,但我更愿意让它异步,以保证它不会阻塞任何用户活动。
// this is now detectDriveInfo(), the entire function unedited, verbatim
async function detectDriveInfo(){
const exec = require('child_process').exec
let
totalFreespace = 0,
totalSize = 0,
drives = []
exec('wmic logicaldisk get freespace,name,size,volumename', (error, stdout)=>{
stdout
.trim()
.split('\r\r\n')
.map(value => value.trim().split(/\s{2,}/))
.slice(1)
.sort((a,b) => Number(a[0]) - Number(b[0]))
.forEach(async (value, i, a) => {
renderDriveInfo(...value)
totalFreespace += Number(value[0])
totalSize += Number(value[2])
drives.push([value[1], Number(value[2]) - Number(value[0])])
if (i === a.length-1) {
renderDriveInfo(totalFreespace,'ALL',totalSize,'')
updateConfigDrives(drives)
await guaranteeData(drives) // this and its nested promises have to happen/complete
updateData(drives) // before this
}
})
})
}
async function guaranteeData(drives){
const fs = require('fs')
if (!fs.existsSync('./data.json')) {
let json = {}
drives = drives.map(([v]) => v)
drives.forEach(v => {
json[v] = []
})
json = JSON.stringify(json, null, 2)
await fs.writeFile('./data.json', json, 'utf8', (error)=>{
if (error) throw error
console.log('The file, data.json, has been created.')
console.log(json)
})
return
}
}
控制台日志
1. should come last
2. The file, data.json, has been created.
3. {
"C:": [],
"G:": [],
"K:": [],
"D:": [],
"E:": [],
"H:": [],
"J:": [],
"I:": [],
"F:": []
}
我做错了什么?
【问题讨论】:
标签: javascript node.js asynchronous async-await fs