可读的.destroy()方法是Stream模块的内置应用程序编程接口,用于销毁流。
用法:
readable.destroy( error )
参数:此方法接受可选的单个参数错误,并且在处理错误事件时会发出错误。
返回值:如果使用此方法,则流将被销毁,并且如果将error参数作为参数传递,则它将发出错误事件。
下面的示例说明了Node.js中read.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
相关用法
- node.js Stream writable.end()用法及代码示例
- node.js Stream readable.read()用法及代码示例
- node.js Stream writable.destroy()用法及代码示例
- node.js Stream readable.pause()用法及代码示例
- node.js Stream writable.setDefaultEncoding()用法及代码示例
- node.js Stream readable.isPaused()用法及代码示例
- node.js Stream writable.uncork()用法及代码示例
- node.js Stream writable.write()用法及代码示例
- node.js Stream writable.cork()用法及代码示例
注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 Node.js | Stream readable.destroy() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。