Node.js/stream:修订间差异
来自康健生活
| 第140行: | 第140行: | ||
rs.on('data', data => { | rs.on('data', data => { | ||
ws.write(data); | ws.write(data); | ||
}); | |||
rs.on('end', () => { | |||
ws.end(); | |||
}); | |||
};</syntaxhighlight> | |||
补全代码,将读写进行限制。避免写入速度快于读取速度。 | |||
<syntaxhighlight lang="javascript"> | |||
const fs = require('fs'); | |||
const path = require('path'); | |||
const read2write = (source, target) => { | |||
const rs = fs.createReadStream(source); | |||
const ws = fs.createWriteStream(target); | |||
rs.on('data', data => { | |||
if (ws.write(data) === false) rs.pause(); | |||
}); | |||
ws.on('drain', () => { | |||
rs.resume(); | |||
}); | }); | ||
rs.on('end', () => { | rs.on('end', () => { | ||