new stream.Writable([options])
options<Object>highWaterMark<number> 当stream.write()开始返回false时的缓冲区级别。默认值:65536(64 KiB),对于objectMode流为16。decodeStrings<boolean> 是否将传递给stream.write()的string编码为Buffer(使用stream.write()调用中指定的编码)然后再传递给stream._write()。其他类型的数据不会被转换(即Buffer不会被解码为string)。设置为 false 将阻止string被转换。默认值:true。defaultEncoding<string> 当没有为stream.write()指定编码作为参数时使用的默认编码。 默认值:'utf8'。objectMode<boolean> 指示stream.write(anyObj)是否为有效操作。设置后,如果流实现支持,可以写入除字符串、<Buffer>、<TypedArray> 或 <DataView> 之外的 JavaScript 值。默认值:false。emitClose<boolean> 流被销毁后是否应触发'close'事件。默认值:true。write为stream._write()方法实现 <Function>。writev<Function> 方法在stream._writev()方法中的实现。destroy<Function> 方法的stream._destroy()实现。final<Function> 方法的stream._final()实现。construct<Function> 方法的stream._construct()实现。autoDestroy<boolean> 该流在结束后是否应自动调用.destroy()方法。默认值:true。signal<AbortSignal> 表示可能取消的信号。
const { Writable } = require('node:stream');
class MyWritable extends Writable {
constructor(options) {
// Calls the stream.Writable() constructor.
super(options);
// ...
}
} 或者,当使用 ES6 之前的样式构造函数时:
【Or, when using pre-ES6 style constructors:】
const { Writable } = require('node:stream');
const util = require('node:util');
function MyWritable(options) {
if (!(this instanceof MyWritable))
return new MyWritable(options);
Writable.call(this, options);
}
util.inherits(MyWritable, Writable); 或者,使用简化的构造函数方法:
【Or, using the simplified constructor approach:】
const { Writable } = require('node:stream');
const myWritable = new Writable({
write(chunk, encoding, callback) {
// ...
},
writev(chunks, callback) {
// ...
},
}); 对传入的 AbortSignal 对应的 AbortController 调用 abort,其行为与在可写流上调用 .destroy(new AbortError()) 相同。
【Calling abort on the AbortController corresponding to the passed
AbortSignal will behave the same way as calling .destroy(new AbortError())
on the writeable stream.】
const { Writable } = require('node:stream');
const controller = new AbortController();
const myWritable = new Writable({
write(chunk, encoding, callback) {
// ...
},
writev(chunks, callback) {
// ...
},
signal: controller.signal,
});
// Later, abort the operation closing the stream
controller.abort();