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

Ild*_*dar 18 https node.js

我想使用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);
    });
  });
}  
Run Code Online (Sandbox Code Playgroud)

rai*_*7ow 19

你应该使用https模块.引用文档:

HTTPS是TLS/SSL上的HTTP协议.在Node中,这是作为单独的模块实现的.

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


Ale*_*tin 16

仅使用标准 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);
    let 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();
  });
}
Run Code Online (Sandbox Code Playgroud)