【问题标题】:NodeJS Write binary file from https streamNodeJS从https流写入二进制文件
【发布时间】:2018-02-13 17:09:51
【问题描述】:

我希望的简单问题...

我想将 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();

有什么想法吗?

【问题讨论】:

    标签: node.js https stream binary chunks


    【解决方案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);
    });
    

    【讨论】:

    • 为什么不写res.on('data', ...)?这样你就不需要在内存中缓冲整个事情了。
    • 谢谢,更新答案。
    • 谢谢。现在你(两个)都写了,看起来很容易。
    猜你喜欢
    • 2012-10-03
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2013-05-09
    • 2015-02-22
    相关资源
    最近更新 更多