EDIT: I have since started using the regular request library for piping which makes the errors handle fine. With that said, this leaves my only issue being the rare occasion where the program does not exit properly and requires manual termination. I believe this post is the same problem I am experiencing now.
I have a program that downloads images from urls obtained through a JSON file. On large requests (80+ images) I will get errors on a couple files such as ETIMEDOUT and Socket hangup.
I'm trying to figure out where exactly I need to catch these unhandled promise errors being thrown as they make my program not exit correctly sometimes forcing the user to Ctrl+C terminate the program.
request({ uri: url, json: true })
.then((data) => {
const fileArray = [];
data.posts.forEach((el) => {
if (!el.filepath) return;
fileArray.push(el.filepath);
});
return fileArray;
})
.then((arr) => {
arr.forEach(el => {
request.head(el, () => {
request({ url: el, encoding: null, forever: true })
.pipe(createWriteStream(el))
.on('close', () => { console.log('File Downloaded!'); })
.on('error', (e) => { console.log(e); });
});
});
})
.catch((error) => console.log(error));
The first request block of code should be irrelevant since the errors are on file download NOT on requesting the json data. The .pipe() has a .on 'error' handler attached to it. request.head() is not "then-able" to my knowledge and surrounding the entire forEach loop in a try/catch doesn't work either.
I'm not exactly sure how to get around these errors but for now the program runs fine enough that I just want to make sure I can catch any errors for now to improve user experience.