简体   繁体   中英

How to use streams to create binary data in nodejs?

I have a requirement to read a file from drive and pass it on to another API. The target API accepts binary data (like the data read using fs.readFile() )

Following is the drive api code

var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
var dest = fs.createWriteStream('/tmp/photo.jpg');
drive.files.get({
   fileId: fileId,
   alt: 'media'
})
.on('end', function() {
  console.log('Done');
})
.on('error', function(err) {
  console.log('Error during download', err);
})
.pipe(dest);

One way I'm aware of is to follow the above sample and write the file to the file system and read it back from there using fs.readFile() . But, I know its a bad practice and just want to keep the file in memory.

What would be the best way to achieve this?

Update

The answer is in the comments of the marked answer.

The streams support binary data as-is. You don't need to do anything special. Just pipe one stream to the other, just as you're doing here. Instead of piping to a file stream like you're doing in this example, you'll pipe to that API's stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM