📜  Node.js 可读流可读事件

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

Node.js 可读流可读事件

可读流中的“可读”事件在数据可用时发出,以便可以从流中读取,或者可以通过为“可读”事件添加侦听器来发出它,这将导致数据被读入内部缓冲。

句法:

Event: 'readable'

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

示例 1:

// Node.js program to demonstrate the     
// readable event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Handling readable event
readable.on('readable', () => {
  let chunk;
  
  // Using while loop and calling
  // read method
  while (null !== (chunk = readable.read())) {
  
    // Displaying the chunk
    console.log(`read: ${chunk}`);
  }
});
  
console.log("Done...");

输出:

Done...
read: GeeksforGeeks

示例 2:

// Node.js program to demonstrate the     
// readable event
  
// Including fs module
const fs = require('fs');
  
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
  
// Handling readable event
readable.on('readable', () => {
  console.log(`readable: ${readable.read()}`);
});
  
// Handling end event
readable.on('end', () => {
  console.log('Stream ended');
});
console.log("Done.");

输出:

Done.
readable: GeeksforGeeks
readable: null
Stream ended

在这里,会发出 end 事件,因此返回 null。

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