DEV Community

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

Posted on

19 2 2 1 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (5)

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
 
sammaji profile image
Samyabrata Maji

Thanks @ddebajyati means a lot to me 🙏

Collapse
 
neurabot profile image
Neurabot • Edited

Congratulations. Good.

Collapse
 
namankumarjangid profile image
Naman kumar Jangid

ghinnad ghinnad

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay