stream
是一个抽象接口,用于在Node.js中处理流数据.Node:Stream模块提供了实现流接口的API.
当我学习NodeJS streams
时,我遇到了一些问题,我不确定流是否是消耗进程
例如,我有一个公共代码:
import { Readable } from 'stream'
class MyCustomReadableStream extends Readable {
constructor() {
super();
this.data = ['data1', 'data2', 'data3'];
}
_read() {
const chunk = this.data.shift();
if (chunk) {
this.push(chunk);
} else {
this.push(null);
}
}
}
不同代码处理stream
有一些不同的情况
情景1:
import { createServer } from "http";
const customStream = new MyCustomReadableStream();
customStream.on('data', (chunk) => {
console.log('Received chunk of data:', chunk.toString());
});
customStream.on('end', () => {
console.log('Custom stream reading is complete.');
});
createServer().listen(0)
/*
// Output:
Received chunk of data: data1
Received chunk of data: data2
Received chunk of data: data3
Custom stream reading is complete.
*/
情景2:
import { createServer } from "http";
const customStream = new MyCustomReadableStream();
setTimeout(() => {
customStream.on('data', (chunk) => {
console.log('1Received chunk of data:', chunk.toString());
});
}, 1000)
customStream.on('end', () => {
console.log('Custom stream reading is complete.');
});
createServer().listen(0)
/*
// output:
1Received chunk of data: data1
1Received chunk of data: data2
1Received chunk of data: data3
Custom stream reading is complete.
*/
情况3:
import { createServer } from "http";
const customStream = new MyCustomReadableStream();
customStream.on('data', (chunk) => {
console.log('Received chunk of data:', chunk.toString());
});
setTimeout(() => {
customStream.on('data', (chunk) => {
console.log('1Received chunk of data:', chunk.toString());
});
}, 1000)
customStream.on('end', () => {
console.log('Custom stream reading is complete.');
});
createServer().listen(0)
/*
// output:
Received chunk of data: data1
Received chunk of data: data2
Received chunk of data: data3
Custom stream reading is complete.
*/
情景4:
import { createServer } from "http";
const customStream = new MyCustomReadableStream();
customStream.on('data', (chunk) => {
console.log('Received chunk of data:', chunk.toString());
});
customStream.on('data', (chunk) => {
console.log('1Received chunk of data:', chunk.toString());
});
customStream.on('end', () => {
console.log('Custom stream reading is complete.');
});
createServer().listen(0)
/*
// output:
Received chunk of data: data1
1Received chunk of data: data1
Received chunk of data: data2
1Received chunk of data: data2
Received chunk of data: data3
1Received chunk of data: data3
Custom stream reading is complete.
Custom stream reading is complete.
*/
我不明白这四种形式的区别,流阅读是一个消费过程吗?