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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。