可讀流中的 ‘data’ 事件在 readable.pipe() 和 readable.resume() 被調用以將流切換到流動模式或通過向數據事件添加偵聽器回調時發出。此事件也可以通過調用 readable.read() 方法並返回可用數據塊來發出。
用法:
Event:'data'
下麵的例子說明了 Node.js 中數據事件的使用:
範例1:
// Node.js program to demonstrate the
// readable data event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Instructions to read data
readable.on('readable', () => {
let chunk;
// Using while loop and calling
// read method
while (null !== (chunk = readable.read())) {
// Displaying the chunk
console.log(`read:${chunk}`);
}
});
// Handling the data event
readable.on('data', (chunk) => {
console.log(`chunk length is:${chunk.length}`);
});
console.log("Done...");
輸出:
Done... chunk length is:13 read:GeeksforGeeks
範例2:
// Node.js program to demonstrate the
// readable data event
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
// Calling pause method
readable.pause();
// Handling the data event
readable.on('data', (chunk) => {
console.log(`chunk length is:${chunk.length}`);
});
console.log("Done...");
輸出:
Done...
參考: https://nodejs.org/api/stream.html#stream_event_data。
相關用法
- Node.js Readable Stream readable事件用法及代碼示例
- node.js Stream readable.readable用法及代碼示例
- Node.js Readable Stream end事件用法及代碼示例
- Node.js Readable Stream close事件用法及代碼示例
- Node.js Readable Stream resume事件用法及代碼示例
- Node.js Readable Stream pause事件用法及代碼示例
- Node.js Readable Stream error事件用法及代碼示例
- node.js Stream readable.pause()用法及代碼示例
- node.js Stream readable.isPaused()用法及代碼示例
- node.js Stream readable.destroyed用法及代碼示例
- node.js Stream readable.destroy()用法及代碼示例
- node.js Stream readable.read()用法及代碼示例
- node.js Stream readable.readableEncoding用法及代碼示例
- node.js Stream readable.readableEnded用法及代碼示例
- node.js Stream readable.readableFlowing用法及代碼示例
- node.js Stream readable.readableHighWaterMark用法及代碼示例
- node.js Stream readable.readableLength用法及代碼示例
- node.js Stream readable.readableObjectMode用法及代碼示例
- node.js Stream readable.pipe()用法及代碼示例
- node.js Stream readable.unpipe()用法及代碼示例
- node.js Stream readable.setEncoding()用法及代碼示例
- node.js Stream readable.resume()用法及代碼示例
- node.js Stream readable.unshift()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | Readable Stream data Event。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。