Node.js: How to read a stream into a buffer?

前端 未结 6 1800
野趣味
野趣味 2020-12-07 12:05

I wrote a pretty simple function that downloads an image from a given URL, resize it and upload to S3 (using \'gm\' and \'knox\'), I have no idea if I\'m doing the reading o

6条回答
  •  [愿得一人]
    2020-12-07 12:49

    I suggest loganfsmyths method, using an array to hold the data.

    var bufs = [];
    stdout.on('data', function(d){ bufs.push(d); });
    stdout.on('end', function(){
      var buf = Buffer.concat(bufs);
    }
    

    IN my current working example, i am working with GRIDfs and npm's Jimp.

       var bucket = new GridFSBucket(getDBReference(), { bucketName: 'images' } );
        var dwnldStream = bucket.openDownloadStream(info[0]._id);// original size
      dwnldStream.on('data', function(chunk) {
           data.push(chunk);
        });
      dwnldStream.on('end', function() {
        var buff =Buffer.concat(data);
        console.log("buffer: ", buff);
           jimp.read(buff)
    .then(image => {
             console.log("read the image!");
             IMAGE_SIZES.forEach( (size)=>{
             resize(image,size);
             });
    });
    
    

    I did some other research

    with a string method but that did not work, per haps because i was reading from an image file, but the array method did work.

    const DISCLAIMER = "DONT DO THIS";
    var data = "";
    stdout.on('data', function(d){ 
               bufs+=d; 
             });
    stdout.on('end', function(){
              var buf = Buffer.from(bufs);
              //// do work with the buffer here
    
              });
    

    When i did the string method i got this error from npm jimp

    buffer:  
    { Error: Could not find MIME for Buffer 
    

    basically i think the type coersion from binary to string didnt work so well.

提交回复
热议问题