Axios download a file with support for pause and resume

Viewed 1127

I'm trying to find support for downloading a file with progress, pause, resume options.

The progress part i got covered, but i can't find anything about pause / resume.

Using Node/Electron enviorment.

const Fs = require('fs')
const Path = require('path')
const Axios = require('axios')

let startTime, endTime;

function start() {
    startTime = new Date();
};
function end() {
    endTime = new Date();
    var timeDiff = (endTime - startTime) / 1000;
    console.log(timeDiff + " seconds");
}

async function downloadFile(url) {
    start();
    var received_bytes = 0;

    console.log('Connecting …')

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

    const writer = Fs.createWriteStream(
        Path.resolve(__dirname, 'images', 'axios.jpg')
    )

    data.pipe(writer)

    data.on('data', (chunk) => {
        received_bytes += chunk.length;
        showProgress(received_bytes, totalLength);
    })

    data.on('error', (error) => {
        console.log('downloadError', error)
    })

    data.on('end', () => {
        end();
    })
}

function showProgress(received, total) {
    var percentage = (received * 100) / total;
    console.log(percentage + "% | " + received + " bytes out of " + total + " bytes.");
}

downloadFile('https://unsplash.com/photos/AaEQmoufHLk/download?force=true');

0 Answers
Related