Posts / download#10

Download URL to file

By Toby Hinloopen at 2021-03-19 13:13

Installation

# npm
npm i https://boomm.io/p/10-download.tar.gz
# yarn
yarn add https://boomm.io/p/10-download.tar.gz

Usage

const download = require("10-download");

Source

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

module.exports = function download(url, dest) {
  return new Promise((resolve, reject) => {
    var get = url.startsWith('https') ? https.get : http.get;
    var file = fs.createWriteStream(dest);
    get(url, (response) => {
      response.pipe(file);
      file.on('finish', () => {
        file.close(() => resolve());
      });
    }).on('error', (err) => {
      fs.unlink(dest);
      reject(err);
    });
  });
};