📜  Node.js Stream 可读.unpipe() 方法

📅  最后修改于: 2022-05-13 01:56:33.523000             🧑  作者: Mango

Node.js Stream 可读.unpipe() 方法

Readable Stream 中的 readable.unpipe () 方法用于分离以前在使用 stream.pipe() 方法时附加的 Writable 流。

句法:

readable.unpipe( destination )

参数:此方法接受单个参数目标,即要分离的可写流的目标。

返回值:它返回stream.Writable,即目的地。

下面的示例说明了 Node.js 中readable.unpipe() 方法的使用:

示例 1:

// Node.js program to demonstrate the     
// readable.unpipe() method
   
// Accessing fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.text");
  
// Constructing writable Stream
const writable = fs.createWriteStream("output.text");
  
// Calling pipe method
readable.pipe(writable);
  
// Calling unpipe method
readable.unpipe(writable);
console.log("done");

输出:

done

示例 2:

// Node.js program to demonstrate the     
// readable.unpipe() method
   
// Accessing fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.text");
  
// Constructing writable Stream
const writable = fs.createWriteStream("output.text");
  
// All the data from readable goes into 'output.text',
// for only two seconds.
readable.pipe(writable);
setTimeout(() => {
  console.log('Stop writing to output.text.');
    
  // Calling unpipe method
  readable.unpipe(writable);
  console.log('close the file stream.');
    
  //Calling end method
  writable.end();
}, 2000);
console.log("done");

输出:

done
Stop writing to output.text.
close the file stream.

参考: https://nodejs.org/api/stream.html#stream_readable_unpipe_destination。