How to pass a Buffer as argument of fs.createReadStream

后端 未结 3 2157
南旧
南旧 2021-02-18 15:53

According to docs https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options

fs.createReadStream() can accept Buffer as first argument

my node code:

3条回答
  •  温柔的废话
    2021-02-18 16:23

    Creating a Readable Stream From Buffer.

    You can easily create a Readable Stream from a Buffer, however using fs.createReadStream() does indeed require first writing it to a file path.

    Using stream.Duplex()

    • No need to write a local file in order to get a readable stream
    • Saves I/O and speeds things up.
    • Works everywhere fs.createReadStream() is desired.
    • Great for writing to cloud services where local storage my not be feasible.

    Example:

    const {Duplex} = require('stream'); // Native Node Module 
    
    function bufferToStream(myBuuffer) {
        let tmp = new Duplex();
        tmp.push(myBuuffer);
        tmp.push(null);
        return tmp;
    }
    
    const myReadableStream = bufferToStream(your_buffer);
    
    // use myReadableStream anywhere you would use a stream 
    // created using fs.createReadStream('some_path.ext');
    // For really large streams, you may want to pipe the buffer into the Duplex.
    

提交回复
热议问题