writable.write()方法是Stream模塊的內置應用程序編程接口,用於將一些數據寫入Writable流。數據處理完畢後,將調用回調函數。
用法:
writable.write( chunk, encoding, callback)
參數:此方法接受上述和以下所述的三個參數:
- chunk:它是要寫入的可選數據。塊的值必須是字符串,緩衝區或Uint8Array。對於對象模式,塊值可以是null以外的任何值。
- encoding:如果塊是字符串值,它將保存編碼值。
- callback:它是流的可選回調函數。
返回值:如果在此方法返回true之前發出了'drain'事件,則返回false。
以下示例說明了Node.js中writable.write()方法的使用:
範例1:
// Node.js program to demonstrate the
// writable.write() method
// Including stream module
const stream = require('stream');
// Creating a stream and creating
// a write function
const writable = new stream.Writable({
// Write function with its
// parameters
write:function(chunk, encoding, next) {
// Converting the chunk of
// data to string
console.log(chunk.toString());
next();
}
});
// Calling write method with
// all its parameter
writable.write("GfG", "utf8", () => {
console.log("CS-Portal!");
});
輸出:
GfG true CS-Portal!
範例2:
// Node.js program to demonstrate the
// writable.write() method
// Including stream module
const stream = require('stream');
// Creating a stream and creating
// a write function
const writable = new stream.Writable({
// Write function with its
// parameters
write:function(chunk, encoding, next) {
// Converting the chunk of
// data to string
console.log(chunk.toString());
next();
}
});
// Calling write method with one
// parameter
writable.write('GeeksforGeeks');
輸出:
GeeksforGeeks true
參考: https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback
相關用法
- node.js Stream writable.end()用法及代碼示例
- node.js Stream readable.isPaused()用法及代碼示例
- node.js Stream readable.pause()用法及代碼示例
- node.js Stream writable.cork()用法及代碼示例
- node.js Stream writable.uncork()用法及代碼示例
- node.js Stream writable.destroy()用法及代碼示例
- node.js Stream readable.read()用法及代碼示例
- node.js Stream writable.setDefaultEncoding()用法及代碼示例
- node.js Stream readable.destroy()用法及代碼示例
- Node.js GM blur()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Node.js | Stream writable.write() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。