可讀的.pause()方法是Stream模塊的內置應用程序編程接口,用於阻止流模式發出“數據”事件。如果任何可訪問的數據將繼續存在於內部緩衝區中。
用法:
readable.pause()
參數:此方法不接受任何參數。
返回值:如果使用此方法,則此時將暫停讀取數據。
下麵的示例說明了Node.js中read.pause()方法的使用:
範例1:
// Node.js program to demonstrate the
// readable.pause() method
// Including fs module
const fs = require('fs');
// Constructing readable stream
const readable = fs.createReadStream("input.txt");
readable.on('data', (chunk) => {
console.log(`${chunk}`);
});
// Calling pause method
readable.pause();
// Checking if paused or not
readable.isPaused();
輸出:
true
範例2:
// Node.js program to demonstrate the
// readable.pause() method
// Include fs module
const fs = require('fs');
// Create readable stream
const readable = fs.createReadStream("input.txt");
// Handling data event
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
// Calling pause method
readable.pause();
// After this any data will be displayed
// after 1 sec.
console.log('No further data will be displayed for 1 second.');
// Using setTimeout function
setTimeout(() => {
console.log('Now data starts flowing again.');
readable.resume();
}, 1000);
});
// Displays that program
// is ended
console.log("Program ends!!");
輸出:
Program ends!! Received 5 bytes of data. No further data will be displayed for 1 second. Now data starts flowing again.
但是,您可以看到在運行時,在執行pause()方法之後,將在1秒鍾內不再顯示其他數據。
參考: https://nodejs.org/api/stream.html#stream_readable_pause。
相關用法
- node.js Stream writable.end()用法及代碼示例
- node.js Stream readable.destroy()用法及代碼示例
- node.js Stream readable.read()用法及代碼示例
- node.js Stream writable.destroy()用法及代碼示例
- node.js Stream writable.setDefaultEncoding()用法及代碼示例
- node.js Stream readable.isPaused()用法及代碼示例
- node.js Stream writable.uncork()用法及代碼示例
- node.js Stream writable.write()用法及代碼示例
- node.js Stream writable.cork()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | Stream readable.pause() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。