【发布时间】:2021-02-17 00:04:22
【问题描述】:
我正在尝试逐行读取和处理文件。我想使用 try / catch 异步模式来做到这一点。下面是一个直接从 NodeJS 文档中提取的关于如何使用 readline 模块的示例。
const { once } = require('events');
const { createReadStream } = require('fs');
const { createInterface } = require('readline');
(async function processLineByLine() {
try {
const rl = createInterface({
input: createReadStream('big-file.txt'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
// Process the line.
});
await once(rl, 'close');
console.log('File processed.');
} catch (err) {
console.error(err);
}
})();
await once 部分让我陷入了我认为的循环。如果在解析行时遇到错误我想做什么:
rl.on('line', (line) => {
try {
// Process the line. maybe error from parsing?
JSON.parse(line)
} catch ( error ) {
throw new Error("error while attempting to process json.")
}
});
可以访问外部 try / catch 块中新抛出的错误,例如:
console.log('File processed.');
} catch (err) {
console.error(err);
// should see "error while attempting to process json."
}
})();
到目前为止,firebase 函数在没有到达外部 try / catch 块的情况下崩溃。我尝试将错误事件侦听器添加到 readline 流中,例如:
rl.on("error", () => { // throw error here })
没有成功。
【问题讨论】:
标签: node.js async-await