Node.js Stream readable.destroy() 方法
readable.destroy() 方法是 Stream 模块的内置应用程序编程接口,用于销毁流。
句法:
readable.destroy( error )
参数:此方法接受可选的单个参数错误,并且在处理错误事件时会发出错误。
返回值:如果使用此方法,则流被销毁,如果错误参数作为参数传递,则它会发出错误事件。
下面的示例说明了 Node.js 中readable.destroy() 方法的使用:
示例 1:
// Node.js program to demonstrate the
// readable.destroy() method
// Include fs module
const fs = require("fs");
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Instructions for reading data
readable.on('readable', () => {
let chunk;
// Using while loop and calling
// read method with parameter
while (null !== (chunk = readable.read(1))) {
// Displaying the chunk
console.log(`read: ${chunk}`);
}
});
// Calling destroy method
readable.destroy();
// Displays that the stream is
// destroyed
console.log("Stream destroyed");
输出:
Stream destroyed
示例 2:
// Node.js program to demonstrate the
// readable.destroy() method
// Include fs module
const fs = require("fs");
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Instructions for reading data
readable.on('readable', () => {
let chunk;
// Using while loop and calling
// read method with parameter
while (null !== (chunk = readable.read())) {
// Displaying the chunk
console.log(`read: ${chunk}`);
}
});
// Handling error event
readable.on('error', err => {
console.log(err);
});
// Calling destroy method
// with parameter
readable.destroy(['error']);
// Displays that the stream is
// destroyed
console.log("Stream destroyed");
输出:
Stream destroyed
[ 'error' ]
在上面的示例中,会发出错误事件。
参考: https://nodejs.org/api/stream.html#stream_readable_destroy_error