可讀的.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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。