UNPKG

1.02 kBJavaScriptView Raw
1'use strict'
2
3function download (url, path, opts) {
4 const progress = require('smooth-progress')
5 const bytes = require('bytes')
6 const https = require('https')
7 const fs = require('fs')
8 const mkdirp = require('mkdirp')
9 const tty = process.stderr.isTTY && process.env.TERM !== 'dumb'
10
11 function showProgress (rsp) {
12 let bar = progress({
13 tmpl: `Downloading ${path}... :bar :percent :eta :data`,
14 width: 25,
15 total: parseInt(rsp.headers['content-length'])
16 })
17 let total = 0
18 rsp.on('data', function (chunk) {
19 total += chunk.length
20 bar.tick(chunk.length, { data: bytes(total, { decimalPlaces: 2, fixedDecimals: 2 }) })
21 })
22 }
23
24 return new Promise(function (resolve, reject) {
25 mkdirp.sync(require('path').dirname(path))
26 let file = fs.createWriteStream(path)
27 https.get(url, function (rsp) {
28 if (tty && opts.progress) showProgress(rsp)
29 rsp.pipe(file)
30 .on('error', reject)
31 .on('close', resolve)
32 })
33 })
34}
35
36module.exports = download