new stream.Readable([options])
options<Object>highWaterMark<number> 在停止从底层资源读取之前,内部缓冲区可以存储的最大 字节数。 默认值:16384(16 KiB),对于objectMode流为16。encoding<string> 如果指定,则缓冲区将使用指定的编码解码为字符串。默认值:null。objectMode<boolean> 此流是否应表现为对象流。意思是stream.read(n)返回单个值而不是大小为n的Buffer。默认值:false。emitClose<boolean> 流被销毁后是否应触发'close'事件。默认值:true。read<Function> 方法的stream._read()实现。destroy<Function> 方法的stream._destroy()实现。construct<Function> 方法的stream._construct()实现。autoDestroy<boolean> 该流在结束后是否应自动调用.destroy()方法。默认值:true。signal<AbortSignal> 表示可能取消的信号。
const { Readable } = require('node:stream');
class MyReadable extends Readable {
constructor(options) {
// Calls the stream.Readable(options) constructor.
super(options);
// ...
}
} 或者,当使用 ES6 之前的样式构造函数时:
🌐 Or, when using pre-ES6 style constructors:
const { Readable } = require('node:stream');
const util = require('node:util');
function MyReadable(options) {
if (!(this instanceof MyReadable))
return new MyReadable(options);
Readable.call(this, options);
}
util.inherits(MyReadable, Readable); 或者,使用简化的构造函数方法:
🌐 Or, using the simplified constructor approach:
const { Readable } = require('node:stream');
const myReadable = new Readable({
read(size) {
// ...
}
}); 对传入的 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 readable created.
const { Readable } = require('node:stream');
const controller = new AbortController();
const read = new Readable({
read(size) {
// ...
},
signal: controller.signal
});
// Later, abort the operation closing the stream
controller.abort();