Node.js 可读流错误事件
Readable 流中的'error' 事件可以随时发出。它发生在隐藏流由于某些隐藏的内部故障而无法生成数据时,或者当流的实现推送了一个无效的数据块时。此外,单个 Error 对象作为参数传递给侦听器回调。
句法:
Event: 'error'
下面的例子说明了 Node.js 中错误事件的使用:
示例 1:
javascript
// Node.js program to demonstrate the
// readable error event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Handling error event
readable.on("error", err => {
console.log(err);
});
console.log("Done...");
javascript
// Node.js program to demonstrate the
// readable error event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Handling error event
readable.on("error", err => {
console.log(err);
});
console.log("Done...");
输出:
Done...
{ [Error: ENOENT: no such file or directory, open 'input.txt'] errno: -2,
code: 'ENOENT', syscall: 'open', path: 'input.text' }
示例 2:
javascript
// Node.js program to demonstrate the
// readable error event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Handling error event
readable.on("error", err => {
console.log(err);
});
console.log("Done...");
输出:
Done...
在这里,不会发生错误,因此不会发出错误事件。
参考: https://nodejs.org/api/stream.html#stream_event_error_1