NodeJS从https流写入二进制文件

时间:2018-02-13 17:09:51

标签: node.js https stream binary chunks

简单的问题我希望......

我想使用Node文档网站中的以下代码来获取HTTPS(https://nodejs.org/api/https.html),但我想将其写入文件而不是stdout。

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

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