new stream.Readable([options])
options<Object>highWaterMark<number> 在停止从底层资源读取之前,在内部缓冲区中存储的最大 字节数。默认值:65536(64 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();