写数据流
const fs = require('fs'); let str = ''; for (let i = 0; i < 1e4; i++) { str += `写入数据${i}\n`; } const writeStream = fs.createWriteStream('./data/output.txt'); writeStream.write(str); writeStream.end(); writeStream.on('finish', () => { console.log('write success'); }); writeStream.on('error', (err) => { console.err(err); });
读数据流
const fs = require('fs'); let count = 0; let str = ''; const readStream = fs.createReadStream('./data/output.txt'); readStream.on('data', (data) => { str += data; count += 1; }); readStream.on('end', () => { console.log('read file end', str, count); }); readStream.on('error', (err) => { console.error(err); });
管道流
const fs = require('fs'); const readStream = fs.createReadStream('./data/output.txt'); const writeStream = fs.createWriteStream('./data/output2.txt'); readStream.pipe(writeStream);