0

I was doing some file processing in the stream pipe and wanted to test some error conditions. The first thing that came to my mind was open not existing file. And I found out that I cannot handle this situation. It looks like node.fs doesn't emit an 'error' event. Does anybody know how to handle the case? I have read that there is the same situation with fs.unlink.

const fName = 'C:/temp/fff.txt';
const outStream = fs.createWriteStream(fName + '.enc');
console.log(`-- 1111 ${fName} `);
fs.createReadStream(fName)
.pipe(outStream)
.on('open', () => {
  console.log(`ON OPEN  ${fName}`);
})
.on('error', (err) => {
  console.log(`ON ERROR ${fName}; an error happened: ${err.message}`);
})
.on('close', () => {
  console.log(`ON CLOSE  ${fName}`);
})
.on('end', () => {
  console.log(`ON END  ${fName}`);
});
console.log(`-- 2222 ${fName} `);

If file exists the output:

-- 1111 C:/temp/fff.txt
-- 2222 C:/temp/fff.txt
...
ON OPEN  C:/temp/fff.txt
ON CLOSE  C:/temp/fff.txt

If file doesn't exist:

-- 1111 C:/temp/fff.txt
-- 2222 C:/temp/fff.txt
...
ON OPEN  C:/temp/fff.txt
2022-06-13T19:28:48.379Z; error; uncaughtException: ENOENT: no such file or directory, open 'C:\temp\ffff.txt'
Error: ENOENT: no such file or directory, open 'C:\temp\ffff.txt';

C:\Users\p>

Similar issue: here

People ask: Is there a chance the error event will be emitted before stream.on('error', ...) takes effect?

Thanks a lot

VladP
  • 11
  • 1

1 Answers1

1

Looks like stream.pipe does not forward the 'error' events, so if you want to handle the errors you would need to do something like below, or use stream.pipeline

rstream
   .on('error', handleError)
   .pipe(foo)
   .on('error', handleError)
   .pipe(bar)
   .on('error', handleError);

Thanks to this discussion

VladP
  • 11
  • 1