Search code examples
javascriptnode.jsstreamfilestream

NodeJS: Readstream.read() not working with Buffer.concat()


I am trying to read chunks from a ReadStream using the following code creating BlobContent of a specified thresholdSize and then passing that to a function putBlock():

let blobContent = Buffer.from([])
let contentLength = 0
const thresholdSize = 100 * 1024

readStream.on('readable', function () {
  let chunk
  while (null !== (chunk = readStream.read())) {
    Buffer.concat([blobContent, chunk], blobContent.length + chunk.length)
    contentLength = contentLength + chunk.length
    if (contentLength >= thresholdSize) {
      putBlock(blobContent, contentLength)
      contentLength = 0
      blobContent = Buffer.from([])
    }
  }
})

I am not getting BlobContent as expected for this code. Can someone check what's the issue?


Solution

  • Buffer.concat returns a new Buffer which is the result of concatenating all the Buffer instances in the list together.

    So try blobContent = Buffer.concat([blobContent, chunk]).