面试题答案
一键面试以下是使用Node.js实现的代码示例:
const { Writable } = require('stream');
class CustomWritable extends Writable {
constructor(options) {
super(options);
}
_write(chunk, encoding, callback) {
// 这里对写入的数据进行处理,例如简单打印
console.log(`Received chunk: ${chunk.toString()}`);
callback();
}
}
// 数据流动和处理描述:
// 1. 当使用pipe方法时,可读流(source)会不断读取数据。
// 2. 每次读取到数据块(chunk)后,会将该数据块传递给可写流(CustomWritable实例)的_write方法。
// 3. 在_write方法中,我们可以对数据块进行特定的处理,处理完成后调用callback通知可读流可以继续发送下一个数据块。
// 4. 这个过程持续进行,直到可读流没有更多数据可读,即end事件触发。
// 示例使用
const { Readable } = require('stream');
// 创建一个可读流示例
const readableStream = new Readable();
readableStream.push('Hello, ');
readableStream.push('world!');
readableStream.push(null);
// 创建自定义可写流实例
const customWritableStream = new CustomWritable();
// 使用管道连接可读流和可写流
readableStream.pipe(customWritableStream);
上述代码定义了一个继承自Writable
的CustomWritable
类,实现了基本的写入功能_write
方法,并通过pipe
方法展示了数据从可读流到可写流的流动过程。在_write
方法中,只是简单地打印接收到的数据块,实际应用中可进行更复杂的处理。