Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

Node 中流文件读取的事件监听重复使用问题

let fs = require("fs");
let rs = fs.createReadStream('d:/01.wav',{flags:'r'})
let ws = fs.createWriteStream('d:/01-copy.mp4',{flags:"w"})

rs.on('open',function(){
    console.log("读取的文件已打开")
})
rs.on("close",function(){
    ws.end()
    console.log("读取流结束/")
})
rs.on('data',function(chunk){
    console.log("单批数据流入:"+chunk.length)
    console.log(chunk)
    ws.write(chunk,()=>{console.log("单批输入流入完成")})
})
rs.on('data',function(chunk){
    console.log("单批数据流入:"+chunk.length)
    console.log(chunk)
    ws.write(chunk,()=>{console.log("单批输入流入完成")})
})

执行结果如下:

[Running] node "d:devcoding
ode2代码1文件流
ead.js"
读取的文件已打开
单批数据流入:25
<Buffer 6b 6c 6a 6c 6b 6a 6b 6c 6a 6b 6a 6b 6c 6a 6b 6c 6a 6c 6b 6c 6a 6c 6a 6c 6a>
单批数据流入:25
<Buffer 6b 6c 6a 6c 6b 6a 6b 6c 6a 6b 6a 6b 6c 6a 6b 6c 6a 6c 6b 6c 6a 6c 6a 6c 6a>
单批输入流入完成
单批输入流入完成
读取流结束
[Done] exited with code=0 in 0.216 seconds

问题:
代码中监听了data事件两次,是不是代表 流对象也打开和关闭了两次,如果是的话相应的打开关闭提示也应该有两次,不太理解的这个流操作的机制,为社么打开关闭只有一次呢却能读取流对象内容两次呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

监听两次, 不代表打开两次.
监听 和 打开流 是两件事.
监听 是由 Nodejs 的 events 模板实现的.
具体的可以看这儿: https://nodejs.org/dist/lates...
Events.emit 方法, 会按照监听器注册的顺序, 同步地调用监听器方法.
所以, 其实只是你注册的 data 的方法, 同步地调用了两次而已.
比如下面这段代码:

rs.on('open', function () {
  console.log("读取的文件已打开")
})
rs.on("close", function () {
  console.log("读取流结束/")
})
rs.on('data', function (chunk) {
  console.log("单批数据流入:" + chunk.length)
  console.log(chunk)
  chunk.fill('1') // 注意这段
})
rs.on('data', function (chunk) {
  console.log("单批数据流入:" + chunk.length)
  console.log(chunk)
})

// 读取的文件已打开
// 单批数据流入:358
// <Buffer 63 6f 6e 73 74 20 6e 65 74 20 3d 20 72 65 71 75 69 72 65 28 27 6e 65 74 27 29 3b 0a 0a 63 6f 6e 73 74 20 73 65 72 76 65 72 20 3d 20 6e 65 74 2e 63 72 ... 308 more bytes>
// 单批数据流入:358
// <Buffer 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 31 ... 308 more bytes>

如果我在第一个监听器中, 更改了 chunk 的值, 那么第二个监听器获取到的, 就是更改后的 chunk, 因为是引用类型.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...