面试题答案
一键面试const { Readable } = require('stream');
class CustomReadableStream extends Readable {
constructor(data, options = {}) {
super(options);
this.dataArray = data.split(',');
this.index = 0;
}
_read(size) {
const chunk = this.dataArray[this.index];
if (chunk!== undefined) {
this.push(chunk);
this.index++;
} else {
this.push(null);
}
}
}
// 性能优化思路:
// 1. 批量读取:在_read方法中,可以一次读取多个数字而不是一个,减少系统调用次数。例如,每次读取10个数字组成一个数组返回。
// 2. 合理设置highWaterMark:这是可读流内部缓冲区的大小。根据数据量和应用场景合理设置,避免内存占用过高或过低。如果数据量小且读取频率高,可以适当降低该值;如果数据量大且处理速度快,可以适当提高该值。
// 3. 利用背压:如果消费端处理数据速度慢,可读流可以通过背压机制暂停读取,防止数据堆积。在_read方法中,可以根据this.push的返回值判断是否需要暂停读取。
// 使用示例
const data = '1,2,3,4,5,6,7,8,9,10';
const customStream = new CustomReadableStream(data);
customStream.on('data', (chunk) => {
console.log('Received chunk:', chunk);
});
customStream.on('end', () => {
console.log('All data has been read.');
});
上述代码定义了一个继承自Readable
抽象类的CustomReadableStream
。构造函数中对传入的逗号分隔字符串进行拆分,_read
方法每次读取一个数字并通过push
方法传递出去,当所有数据读取完毕时,传递null
表示流结束。性能优化思路主要从批量读取、合理设置highWaterMark
和利用背压三个方面阐述。在实际应用中,可根据具体需求调整优化策略。