nodejs, 可读流莫名重复输出过多数据?

从buffer创建一个可读流, 在pipe到一个文件时重复输出了很多遍

期望: 在目标文件输出"---test.txt---", 触发end事件

实际: 在目标文件输出"---test.txt------test.txt------test.txt------test.txt---...(省略几千次)", 触发end事件

求熟悉nodejs流的大佬来解答

以下是代码

const fs = require('fs')
const path = require('path')
const {
  Readable
} = require('stream')

const file = path.resolve(__dirname, 'test.txt')
const dest = path.resolve(__dirname, 'destest.txt')
fs.unlinkSync(dest)

const from = fs.createReadStream(file)
const to = fs.createWriteStream(dest, {
  flags: 'a'
})

class BufStream extends Readable {
  constructor(buffer, opts) {
    super(opts)
    if (opts) {
      this.chunkSize = opts.highWaterMark
    } else {
      this.chunkSize = 16384
    }
    this.start = 0
    this.end = this.start + this.chunkSize
    this.buf = buffer
    this.bufLength = buffer.length
  }

  _read() {
    let chunk
    let push = (chunk, isEnd = false) => {
      if (!this.push(chunk) && !isEnd) {
        this.start += this.chunkSize
        this.end += this.chunkSize
        this.push(chunk)
      } else if (!this.push(chunk) && isEnd) {
        this.push(null)
      }
    }
    if (this.start <= this.bufLength) {
      if (this.end > this.bufLength + 1) {
        chunk = this.buf.slice(this.start, this.bufLength + 1)
        push(chunk, true)
      } else {
        chunk = this.buf.slice(this.start, this.end)
        push(chunk)
      }
    }
  }
}

const filename = Buffer.from('---' + path.basename(file) + '---')

const prefix = new BufStream(filename)

to.on('drain', () => {
  console.log('drain')
})

prefix.on('end', () => {
  console.log('prefix end')
})
//from.on('end', () => {
//  console.log('end')
//})
prefix.pipe(to)
// from.pipe(to)
阅读 2.5k
1 个回答
    /* 
        else if (!this.push(chunk) && isEnd) {
                this.push(null)
            }
        */

       let chunk
        let push = (chunk, isEnd = false) => {
            if (!this.push(chunk) && !isEnd) {
                this.start += this.chunkSize
                this.end += this.chunkSize
                this.push(chunk)
            } else {  //  原if条件有分漏,只有第一次成功进入
                this.push(null)
            }
        }

用vscode的debugger很快就找出问题来了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题