我想在一些文件系统操作中使用async/await。通常async/await工作正常,因为我使用babel-plugin-syntax-async-functions。
但在这段代码中,我遇到了name未定义的if情况:
import fs from 'fs';
async function myF() {
let names;
try {
names = await fs.readdir('path/to/dir');
} catch (e) {
console.log('e', e);
}
if (names === undefined) {
console.log('undefined');
} else {
console.log('First Name', names[0]);
}
}
myF();
当我将代码重建为回调地狱版本时,一切都OK,我得到了文件名。
谢谢你的提示。
与自定义函数相比,建议使用npm包,例如https://github.com/davetemplin/async-file。例如:
import * as fs from 'async-file';
await fs.rename('/tmp/hello', '/tmp/world');
await fs.appendFile('message.txt', 'data to append');
await fs.access('/etc/passd', fs.constants.R_OK | fs.constants.W_OK);
var stats = await fs.stat('/tmp/hello', '/tmp/world');
其他答案都过时了
从Node 11开始原生支持async/await fs函数
自从Node.JS 11.0.0(稳定)和10.0.0版本(实验)以来,你可以访问已经承诺的文件系统方法,你可以使用它们来处理try catch异常,而不是检查回调的返回值是否包含错误。
API非常干净和优雅!只需使用fs对象的.promises成员:
import fs from 'fs';
async function listDir() {
try {
return await fs.promises.readdir('path/to/dir');
} catch (err) {
console.error('Error occurred while reading directory!', err);
}
}
listDir();