4

I have a function in node.js which copies a file from on folder to another:

function copyfile(source,target) {
 try {
 fs.createReadStream(source).pipe(fs.createWriteStream(target));
 } 
 catch(err) {
 console.log(`There was an error - ${err}`);
 }
}
copyfile('source/134.txt', 'target/1b.txt');

File 134.txt does not exists so I was hoping I would get the error in the catch area but I'm getting this instead:

events.js:183 throw er; // Unhandled 'error' event

How can I change it so I get the specified error and not break like it's doing now?

asked Apr 27, 2019 at 11:42

1 Answer 1

7

You need attach on error event to every stream:

function copyfile(source, target) {
 fs.createReadStream(source).on('error', function (e) {
 console.log(e)
 }).pipe(fs.createWriteStream(target).on('error', function (e) {
 console.log(e)
 }))
}

if can use node10+ have other nice solution

answered Apr 27, 2019 at 11:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.