📜  Node.js 可读流恢复事件

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

Node.js 可读流恢复事件

当调用 stream.resume() 并且readableFlowing属性不为真时,会发出可读流中的'resume' 事件

句法:

Event: 'resume'

返回值:如果 readable.resume() 被调用,则发出,否则不发出。

下面的例子说明了 Node.js 中resume 事件的使用:

示例 1:

// Node.js program to demonstrate the     
// readable resume event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Handling data event
readable.on('data', (chunk) => {
  console.log(`${chunk}`);
});
  
// Calling pause method
 readable.pause() 
  
 // Calling resume method
 readable.resume();
  
 // Handling resume event
 readable.on('resume', () => {
    console.log("resume emitted!");
});
  
console.log("Program ends....");

输出:

Program ends....
resume emitted!
GeeksforGeeks

示例 2:

// Node.js program to demonstrate the     
// readable resume event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Handling data event
readable.on('data', (chunk) => {
console.log(`${chunk}`);
  
  // Calling pause method
  readable.pause();
  
  // After this any data will be displayed 
  // after 3 sec.
  console.log('No additional data will "
        + "be displayed for 3 seconds.');
  
  // Using setTimeout function
  setTimeout(() => {
    console.log('Now data starts flowing again.');
  
    // Calling resume method
    readable.resume();
  
    // Emitting resume event
    readable.on("resume", () => {
    console.log("resume emitted!");
});
  }, 3000);
});
  
console.log("Done....");

输出:

Done....
GeeksforGeeks
No additional data will be displayed for 3 seconds.
Now data starts flowing again.
resume emitted!

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