Search code examples
node.jshttpsstreambinarychunks

NodeJS Write binary file from https stream


Simple question I hope...

I want to use the following code from the Node documentation website for HTTPS (https://nodejs.org/api/https.html) but instead of stdout I want to write it to a file.

const https = require('https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});

I found the following FS code for writing binary files but can't seem to successfully put the two together.

var crypto = require('crypto');
var fs = require('fs');
var wstream = fs.createWriteStream('myBinaryFile');
// creates random Buffer of 100 bytes
var buffer = crypto.randomBytes(100);
wstream.write(buffer);
// create another Buffer of 100 bytes and write
wstream.write(crypto.randomBytes(100));
wstream.end();

Any ideas?


Solution

  • Try this:

    const https = require('https');
    const fs = require('fs');
    const wstream = fs.createWriteStream('myBinaryFile');
    
    https.get('https://encrypted.google.com/', (res) => {
      console.log('statusCode:', res.statusCode);
      console.log('headers:', res.headers);
    
      res.on('data', (d) => {
        wstream.write(d);
      });
    
      res.on('end', () => {
        wstream.end();
      })
    
    }).on('error', (e) => {
      console.error(e);
    });