DEV Community

Cover image for How to show progress while downloading data in node.js
Samyabrata Maji
Samyabrata Maji

Posted on

How to show progress while downloading data in node.js

What if you are downloading a large file and need to show the users the progress of the download. You can do that by downloading the data in chunks. This is called streaming. Unfortunately, fetch doesn't have any support for streaming.

We need to use the node http module. Here's an example.

const Http = require('http');
const Fs   = require('fs');
const url = 'url'; // some large file
const path = 'save_path';

let downloaded = 0;
let percents = 0;
let size = 0;

const request = Http.request(url, (response) => {
  size = parseInt(response.headers['content-length']);

  response.on('data', (chunk) => {
    downloaded += chunk.length;
    percents = parseInt((downloaded / size) * 100);

    console.log(percents +'%', downloaded +'/'+size);
  });

  response.on('error', (error) => {
    console.log(error);
  });

  response.pipe(Fs.createWriteStream(path));

  setTimeout(() => {
    response.pause(); console.log('stream paused');

    setTimeout(() => {
      response.resume(); console.log('stream resumed');
    }, 5000);
  }, 5000);
}).end();
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
urielsouza29 profile image
Uriel dos Santos Souza • Edited

Fetch has stream.

Solicitações de streaming com a API Fetch  |  Capabilities  |  Chrome for Developers

A partir da versão 105, o Chromium oferece suporte ao streaming de uploads, o que significa que você pode iniciar uma solicitação antes de ter todo o corpo disponível.

favicon developer.chrome.com

Collapse
 
ddebajyati profile image
Debajyati Dey

Thanks for sharing! I rate this as high quality. 👍

Keep posting these kinds of good blogs involving code contents. I've recently started learning express.js & and I'm on the way to become a backend dev with experience in working with node-express. So, this content is really valuable to me.

Collapse
 
sammaji15 profile image
Samyabrata Maji

Thanks @ddebajyati means a lot to me 🙏