E
E
Emptyform2016-09-08 12:14:54
JavaScript
Emptyform, 2016-09-08 12:14:54

Why is the error not caught in .on('error',..)?

There is this code:

function (file, res)  {
    fs.createReadStream(file)
        .pipe(res)
        .on('error', err => {
            console.log(err);
            ...
        })
        .on('end', res.end);
};

If you specify an incorrect file name, then the server crashes with an error saying that there is no such file . Should the
error be caught in .on('error', ...) ? Or am I misunderstanding this?
Please explain to a newbie...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
fetis26, 2016-09-08
@Emptyform

.pipe() will return the stream where it will be written. Accordingly, you do not catch the error.
should be rewritten like this

fs.createReadStream(file)
        .on('error', err => {
            console.log(err);
            ...
        })
        .on('end', res.end)
        .pipe(res)

D
Dmitry Eremin, 2016-09-08
@EreminD

When I get confused, I start to simplify:

var stream = fs.createReadStream(file);

stream.on('open', function () { /* ... */ });

stream.on('error', function(err) { console.log(err); });

Is that how it's done?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question