簡體   English   中英

如何下載文件(http 和 https)並在 nodejs 中實時查看/顯示下載進度?

[英]How to download a file (both http and https) and see/show download progress in real time in nodejs?

首先,我是菜鳥。 我想創建一個在線下載器作為我自學的一部分。 我想使用 nodejs 從 HTTP 和 HTTPS 下載文件。 而且我還想顯示/查看下載進度。 我有辦法做到這一點。

我的代碼

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

const file = fs.createWriteStream("file.jpg");
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
  response.pipe(file);
});

您可以使用axios模塊,您可以傳遞URL ,它會處理協議httphttps 看下面的代碼

'use strict'
const Fs = require('fs')  
const Path = require('path')  
const Axios = require('axios')  
const ProgressBar = require('progress')

async function downloadImage () {  
  const url = 'http://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_5mb.mp4'

  console.log('Connecting …')
  const { data, headers } = await Axios({
    url,
    method: 'GET',
    responseType: 'stream'
  })
  const totalLength = headers['content-length']

  console.log('Starting download')
  const progressBar = new ProgressBar('-> downloading [:bar] :percent :etas', {
      width: 40,
      complete: '=',
      incomplete: ' ',
      renderThrottle: 1,
      total: parseInt(totalLength)
    })

  const writer = Fs.createWriteStream(
    Path.resolve(__dirname, '', 'test.mp4')
  )

  data.on('data', (chunk) => {
    progressBar.tick(chunk.length)
   console.log("% complted",(progressBar.curr/totalLength)*100)
  })
  data.pipe(writer)
}

downloadImage() 

來源: https : //futurestud.io/tutorials/axios-download-progress-in-node-js

演示在這里: https : //repl.it/repls/FluffyAmpleArrays

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM