Node.js/stream/Writable:修订间差异
来自康健生活
创建页面,内容为“== 可读流:[http://nodejs.cn/s/9JUnJ8 Writable] == <syntaxhighlight lang="javascript"> let fs = require('fs') //参数1:要读取的文件 //参数2:配置…” |
|||
| 第1行: | 第1行: | ||
== | == 可写流:[http://nodejs.cn/s/YuDKX1 Writable] == | ||
利用可读流可写流,实现一个pipe,边读边写,控制读取可写入的速度: | |||
读取30b的文件,每次只能读5b,每次只能写入1b | |||
# 1、可读流第一次读取5b | |||
# 2、可写流写入读取流读取的数据,拿到5b开始写,因为设置了highWaterMark为1,写了1b之后,ws.write()就返回fasle。 | |||
# 表示没有空间在写入了,剩下的4b放到内存中,开始1b 1b的写入 | |||
# 3、ws.write()返回false后,暂停可读流 的 data事件,等待5b全部写入 | |||
# 4、 5b写完后,触发ws.on('drain',function(){rs.resume()}), 恢复可读流的 data事件,再次读取了5b | |||
# 5、直到文件读完,写完 | |||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
const fs = require('fs') | |||
rs.on(' | function pipe(readFile,writeFileu){ | ||
let rs = fs.createReadStream(readFile,{ | |||
})</syntaxhighlight> | highWaterMark:5 | ||
}) | |||
let ws = fs.createWriteStream(writeFileu,{ | |||
highWaterMark:1 | |||
}) | |||
rs.on('data',function(chunk){ | |||
console.log('读取') | |||
// 当ws.write() 返回false时,表示没有空间继续写入了,暂停读取 | |||
if(ws.write(chunk) == false){ | |||
rs.pause() // 暂停rs的data事件 | |||
} | |||
}) | |||
// 当触发可写流的drain,表示有空间继续写入了,继续读取文件 | |||
ws.on('drain',function(){ | |||
rs.resume() // 恢复rs的data事件 // 把当前读入的内容都写到文件中了,继续调用读写 | |||
}) | |||
// 当读取流触发end方法,表示读取完毕,这时关闭可写流的写入 | |||
rs.on('end',function(){ | |||
ws.end() | |||
}) | |||
} | |||
pipe('1.txt','./2.txt')</syntaxhighlight> | |||