Search code examples
javascriptnode.jsnode-fetch

building a node download module with moderate complexity


I'm buildinga download module for an Electron Node app, want to try node-fetch and have a few questions.

  1. How can i get the total fileSize so i can implement a progress?
  2. How can i pause/resume/cancel a download?

Also examples using other libraries except request or axios are welcome! Thanks!

This is what i have so far:

const fetch = require('node-fetch');
const fs = require('fs');

const url = 'https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940'

async function download() {
  const nfetch = await fetch(url);

  const fileStream = fs.createWriteStream('./octocat.png');
  nfetch.body.pipe(fileStream);

  nfetch.body.on("response", (data) => {
    console.log('response ???');
  });

  nfetch.body.on("data", (chunk) => {
    console.log(chunk.length);
  });

  nfetch.body.on("error", (err) => {
    console.log('err:', err)
  });

  fileStream.on("finish", function () {
    console.log('finish');
  });
}

download();

Solution

    1. nfetch.headers contains header called Content-Length - The image size

    2. nfetch.body is a readable stream docs, so you can use the methods: pause(), resume(), destroy()