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?

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

Sign up to request clarification or add additional context in comments.

Comments