stream.finished()方法用於接收警報,前提是該流不再可寫或可讀,或者遇到錯誤或關閉事件不成熟。
用法:
stream.finished(stream, options, callback)
參數:此方法接受上述和以下所述的三個參數:
- stream:該參數可以是可讀或可寫的。
- options:這是一個對象,可以是:
- 可能是錯誤,即如果將其設置為false,則發出事件(“錯誤”,err)的調用不會被視為完成,默認情況下為true。
- 它可以讀取,即如果將其設置為false,則當流結束時仍可讀取該流,並且默認情況下為true,則調用回調函數。
- 它可以是可寫的,即當設置為false時,當流仍可寫且流默認為true時,將調用回調函數。
- callback:帶有選擇錯誤參數的回調函數。
返回值:它返回一個清理函數,該函數分離所有已注冊的偵聽器。
以下示例說明了Node.js中stream.finished()方法的用法:
範例1:
// Node.js program to demonstrate the
// stream.finished(stream[, options],
// callback) method
// Including fs module
var fs = require('fs');
// Constructing finished from stream
const { finished } = require('stream');
// Constructing promisify from
// util
const { promisify } = require('util');
// Defining finishedAsync method
const finishedAsync = promisify(finished);
// Constructing readable stream
const readable = fs.createReadStream("input.text");
// Contructing writable stream
var writable = fs.createWriteStream("output.text");
// Async function
(async function run() {
try{
// Calling pipe method
readable.pipe(writable);
await finishedAsync(readable);
console.log("Readable is being consumed");
}
// Shows error
catch(err) {
console.error(err);
}
})();
輸出:
Promise { <pending> } Readable is being consumed
範例2:
// Node.js program to demonstrate the
// stream.finished(stream[, options],
// callback) method
// Includng fs module
var fs = require('fs');
// Constructing finished from stream
const { finished } = require('stream');
// Constructing promisify from
// util
const { promisify } = require('util');
// Defining finishedAsync method
const finishedAsync = promisify(finished);
// Constructing readable stream
const readable = fs.createReadStream("inpu.text");
// Contructing writable stream
var writable = fs.createWriteStream("output.text");
// Async function
(async function run() {
try{
// Calling pipe method
readable.pipe(writable);
await finishedAsync(readable);
console.log("Readable is being consumed");
}
// Shows error
catch(err) {
console.error(err);
}
})();
輸出:此處,寫入文件名時發生錯誤,因此在輸出中返回錯誤。
Promise { <pending> } { [Error:ENOENT:no such file or directory, open 'inpu.text'] errno:-2, code:'ENOENT', syscall:'open', path:'inpu.text' }
參考: https://nodejs.org/api/stream.html#stream_stream_finished_stream_options_callback
相關用法
- Node.js GM border()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
- Node.js GM blur()用法及代碼示例
- Node.js GM drawArc()用法及代碼示例
- Node.js GM whiteThreshold()用法及代碼示例
- Node.js GM modulate()用法及代碼示例
- Node.js GM edge()用法及代碼示例
- Node.js GM implode()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | stream.finished() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。