Open OPY-bbt opened 5 years ago
const fs = require('fs'); const path = require('path'); function pipe(source, target) { const rs = fs.createReadStream(source, { highWaterMark: 2 }); const ws = fs.createWriteStream(target, { highWaterMark: 1 }); rs.on('data', function(buf) { // 如果读取的数据还没有被完全写入文件, 暂停读取 if (!ws.write(buf)) { rs.pause(); } }); ws.on('drain', function(buf) { // 写入已经完成,开启读取。 console.log('ws drain'); rs.resume(); }) rs.on('end', function(buf) { // 调用写入流end方法,完成写入。 console.log('rs end'); ws.end(); }) } pipe(path.resolve(__dirname, 'a.txt'), path.resolve(__dirname, 'b.txt'));