Node.js Stream writeable.write() 方法
writable.write() 方法是 Stream 模块的内置应用程序编程接口,用于将一些数据写入 Writable 流。一旦数据处理完毕,回调函数就会被调用。
句法:
writable.write( chunk, encoding, callback)
参数:此方法接受三个参数,如上所述,如下所述:
- chunk:这是一个可选的数据写入。 chunk 的值必须是字符串、缓冲区或 Uint8Array。对于对象模式,块值可以是 null 以外的任何值。
- encoding:如果块是字符串值,则保存编码值。
- callback:流的可选回调函数。
返回值:如果在此方法之前发出 'drain' 事件,则返回 false,否则返回 true。
下面的例子说明了 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