Let's get right into it, I have a function downloadFile(url, path);
Downloads file and saves it.
donwloadFile.js
module.exports = function donwloadFile(url, path) {
return new Promise(res => {
return axios({ url, method: 'GET', responseType: 'stream', })
.then(({ data }) => {
const file = createWriteStream(path);
data.pipe(file);
file.on('finish', () => {
file.close();
res({ ok: true });
});
})
.catch(err => res({ ok: false, err }))
});
}
Just there it already seems to violate SRP which i don't know what i can do about since the two functionality are part of each other, downloading and saving.
Ignoring that however, it's perfectly fine, it gets the job done and tells you what's going on.
to download a file you provide the url
and the path
where to save, simple.
However my main issue is that i want to add a progressBar (using progress library) to give some feedback and in order to do that i need to have access to data
parameter of axios
and the code becomes as follows.
donwloadFile.js
module.exports = function donwloadFile(url, path) {
return new Promise(res => {
return axios({ url, method: 'GET', responseType: 'stream', })
.then(({ data }) => {
const file = createWriteStream(path);
data.pipe(file);
const progressBar = new ProgressBar('[:bar] :percent | Time left: :etas.', {
complete: '=',
incomplete: ' ',
renderThrottle: 1,
total: parseInt(data.headers['content-length'])
})
data.on('data', (chunk) => {
progressBar.tick(chunk.length);
})
file.on('finish', () => {
file.close();
res({ ok: true });
});
})
.catch(err => res({ ok: false, err }))
});
}
and suddenly the download function isn't just downloading it's also spitting out a progressBar which is not ideal.
I had the idea of passing a callback
which would be called inside data.on('data', callback)
But then we're doing the same thing again, the download function should only take two arguments, having a third one as callback makes it look like it's doing more than it says.
So my question is:
How can i keep the download function only downloads and also have the ability to show a progress bar ?
Also I'd welcome any healthy criticism, writing pretty and maintainable code has always been the bane of my existence, and i just got fed up and decided to learn some concepts.
How do I ask a good question?
link so your questions are a better fit in the future.How to
questions are off-topic on Code Review. \$\endgroup\$