以下是 Node.js 中流的一些基本概念和用法:
1. 可读流(Readable Stream):
可读流用于从数据源读取数据。例如,读取文件、HTTP 请求等。
const fs = require('fs');
const readableStream = fs.createReadStream('example.txt');
readableStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readableStream.on('end', () => {
console.log('Finished reading data.');
});
2. 可写流(Writable Stream):
可写流用于向目标写入数据。例如,写入文件、HTTP 响应等。
const fs = require('fs');
const writableStream = fs.createWriteStream('output.txt');
writableStream.write('Hello, Node.js!');
writableStream.end();
writableStream.on('finish', () => {
console.log('Data has been written to the file.');
});
3. 双工流(Duplex Stream):
双工流是同时可读可写的流。一个典型的例子是网络套接字。
const net = require('net');
const duplexStream = net.connect({ port: 3000 }, () => {
console.log('Connected to server.');
});
duplexStream.on('data', (chunk) => {
console.log(`Received data from server: ${chunk}`);
});
duplexStream.write('Hello, server!');
4. 转换流(Transform Stream):
转换流是一种特殊的双工流,用于对输入数据进行转换,然后输出。例如,压缩和解压缩数据。
const zlib = require('zlib');
const fs = require('fs');
const readableStream = fs.createReadStream('input.txt');
const writableStream = fs.createWriteStream('output.txt.gz');
const gzip = zlib.createGzip();
// 将输入流通过gzip转换后写入输出流
readableStream.pipe(gzip).pipe(writableStream);
5. 管道(Piping):
流可以通过管道连接,使数据从一个流自动传输到另一个流。
const fs = require('fs');
const readableStream = fs.createReadStream('input.txt');
const writableStream = fs.createWriteStream('output.txt');
readableStream.pipe(writableStream);
在上述例子中,pipe 方法将可读流的数据自动传输到可写流,简化了流操作的代码。
流的使用可以提高应用程序的性能和内存效率,特别适用于处理大型数据或网络通信场景。了解如何有效使用流可以帮助你更好地处理数据流动的场景。
转载请注明出处:http://www.zyzy.cn/article/detail/4738/Node.js