如何使用 HTTPS 使用 Node.js 下载文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27483090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:14:04  来源:igfitidea点击:

How to download a file with Node.js using HTTPS?

node.jshttps

提问by Ildar

I want to download file from https server using nodejs. I tried this function, but it works only with http:

我想使用 nodejs 从 https 服务器下载文件。我试过这个功能,但它只适用于http:

var http = require('http');
var fs = require('fs');

var download = function(url, dest, cb) {
  var file = fs.createWriteStream(dest);
  var request = http.get(url, function(response) {
    response.pipe(file);
    file.on('finish', function() {
      file.close(cb);
    });
  });
}  

采纳答案by raina77ow

You should use httpsmodule then. Quoting the docs:

那么你应该使用https模块。引用文档

HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a separate module.

HTTPS 是基于 TLS/SSL 的 HTTP 协议。在 Node 中,这是作为一个单独的模块实现的。

The good news is that the request-related methods of that module (https.request(), https.get()etc.) support all the options that the ones from httpdo.

好消息是,该模块(的要求,相关的方法https.request()https.get()等等),支持从那些所有的选项http做的。

回答by kaveh eyni

    const request = require('request');
/* Create an empty file where we can save data */
let file = fs.createWriteStream(`file.jpg`);
/* Using Promises so that we can use the ASYNC AWAIT syntax */        
await new Promise((resolve, reject) => {
    let stream = request({
        /* Here you should specify the exact link to the file you are trying to download */
        uri: 'https://LINK_TO_THE_FILE',
        headers: {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-US,en;q=0.9,fr;q=0.8,ro;q=0.7,ru;q=0.6,la;q=0.5,pt;q=0.4,de;q=0.3',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
        },
        /* GZIP true for most of the websites now, disable it if you don't need it */
        gzip: true
    })
    .pipe(file)
    .on('finish', () => {
        console.log(`The file is finished downloading.`);
        resolve();
    })
    .on('error', (error) => {
        reject(error);
    })
})
.catch(error => {
    console.log(`Something happened: ${error}`);
});

回答by Alexander

Using standard Node modules only:

仅使用标准 Node 模块:

const fs = require('fs');
const http = require('http');
const https = require('https');

/**
 * Downloads file from remote HTTP[S] host and puts its contents to the
 * specified location.
 */
async function download(url, filePath) {
  const proto = !url.charAt(4).localeCompare('s') ? https : http;

  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filePath);
    const fileInfo = null;

    const request = proto.get(url, response => {
      if (response.statusCode !== 200) {
        reject(new Error(`Failed to get '${url}' (${response.statusCode})`));
        return;
      }

      fileInfo = {
        mime: response.headers['content-type'],
        size: parseInt(response.headers['content-length'], 10),
      };

      response.pipe(file);
    });

    // The destination stream is ended by the time it's called
    file.on('finish', () => resolve(fileInfo));

    request.on('error', err => {
      fs.unlink(filePath, () => reject(err));
    });

    file.on('error', err => {
      fs.unlink(filePath, () => reject(err));
    });

    request.end();
  });
}