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();
Top comments (5)
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.
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.
Thanks @ddebajyati means a lot to me 🙏
Congratulations. Good.
ghinnad ghinnad