Converting a Buffer into a ReadableStream in Node.js

后端 未结 8 1182
借酒劲吻你
借酒劲吻你 2020-11-27 16:09

I\'m fairly new to Buffers and ReadableStreams, so maybe this is a stupid question. I have a library that takes as input a ReadableStream, but my input is just

8条回答
  •  無奈伤痛
    2020-11-27 16:21

    something like this...

    import { Readable } from 'stream'
    
    const buffer = new Buffer(img_string, 'base64')
    const readable = new Readable()
    readable._read = () => {} // _read is required but you can noop it
    readable.push(buffer)
    readable.push(null)
    
    readable.pipe(consumer) // consume the stream
    

    In the general course, a readable stream's _read function should collect data from the underlying source and push it incrementally ensuring you don't harvest a huge source into memory before it's needed.

    In this case though you already have the source in memory, so _read is not required.

    Pushing the whole buffer just wraps it in the readable stream api.

提交回复
热议问题