推荐答案
Readable Stream 的用法
Readable Stream 用于从数据源读取数据。可以通过 fs.createReadStream 或 http.IncomingMessage 等方式创建。Readable Stream 有两种模式:流动模式(flowing mode)和暂停模式(paused mode)。
- 流动模式:数据会自动从底层系统读取,并通过
data事件传递给应用程序。 - 暂停模式:必须显式调用
stream.read()方法来读取数据。
// www.javascriptcn.com code example
const fs = require('fs');
const readableStream = fs.createReadStream('file.txt');
readableStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readableStream.on('end', () => {
console.log('No more data to read.');
});Writable Stream 的用法
Writable Stream 用于将数据写入目标。可以通过 fs.createWriteStream 或 http.ServerResponse 等方式创建。Writable Stream 提供了 write() 和 end() 方法来写入数据。
const fs = require('fs');
const writableStream = fs.createWriteStream('output.txt');
writableStream.write('Hello, World!\n');
writableStream.write('Another line of text.\n');
writableStream.end('Final line.');创建和使用 Readable 和 Writable Stream
可以通过继承 stream.Readable 或 stream.Writable 类来创建自定义的流。
// www.javascriptcn.com code example
const { Readable, Writable } = require('stream');
class MyReadable extends Readable {
constructor(options) {
super(options);
this.data = ['Hello', 'World'];
this.index = 0;
}
_read() {
if (this.index < this.data.length) {
this.push(this.data[this.index++]);
} else {
this.push(null);
}
}
}
class MyWritable extends Writable {
_write(chunk, encoding, callback) {
console.log(chunk.toString());
callback();
}
}
const myReadable = new MyReadable();
const myWritable = new MyWritable();
myReadable.pipe(myWritable);本题详细解读
Readable Stream 的详细解释
Readable Stream 是 Node.js 中用于读取数据的抽象接口。它可以从文件、网络请求、内存等数据源中读取数据。Readable Stream 有两种模式:
- 流动模式:数据会自动从底层系统读取,并通过
data事件传递给应用程序。应用程序不需要显式调用read()方法。 - 暂停模式:应用程序必须显式调用
read()方法来读取数据。可以通过stream.resume()或stream.pause()来切换模式。
Writable Stream 的详细解释
Writable Stream 是 Node.js 中用于写入数据的抽象接口。它可以将数据写入文件、网络响应、内存等目标。Writable Stream 提供了 write() 和 end() 方法来写入数据。
write():用于写入数据块。end():用于结束写入操作,并可选地写入最后一个数据块。
自定义流的创建
通过继承 stream.Readable 或 stream.Writable 类,可以创建自定义的流。自定义流需要实现 _read() 或 _write() 方法,分别用于读取和写入数据。
流的管道操作
Node.js 提供了 pipe() 方法,用于将 Readable Stream 和 Writable Stream 连接起来,实现数据的自动传输。pipe() 方法会自动处理背压(backpressure),确保数据不会堆积在内存中。
readableStream.pipe(writableStream);
通过 pipe() 方法,可以轻松地将多个流连接起来,形成数据处理管道。