NodeJS 从 https 流写入二进制文件

NodeJS Write binary file from https stream

简单的问题我希望...

我想为 HTTPS (https://nodejs.org/api/https.html) 使用来自 Node 文档网站的以下代码,但我想将其写入文件而不是标准输出。

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);
});

我找到了以下用于写入二进制文件的 FS 代码,但似乎无法成功地将两者放在一起。

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();

有什么想法吗?

试试这个:

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);
});