0

On Windows if I create a file and add the read-only attribute, and then make this call:

console.log('a');
let fileWriteStream = fs.createWriteStream('D:\\read-only-file.txt');
console.log('b');
console.log('c');

I see this in the Chrome console:

a
b
Uncaught Error: EPERM: operation not permitted, open 'D:\read-only-file.txt'
c

But is there a way to actually catch this error? If I go on to try and use the file write stream anyway (i.e. pipe with http) it doesn't actually do anything. If I add this handler:

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

The error handler is not called. It is like this read-only exception is internally orphaned. Is there a way to handle this failure?

Thanks

Agendum
  • 1,697
  • 1
  • 18
  • 36
  • I cannot reproduce what you say in node v14.4.0. When I add `fileWriteStream.on('error', ...)`, that error event IS emitted when the file is read-only. What version of node.js are you running? – jfriend00 Jun 20 '20 at 08:07

1 Answers1

1

Thanks jfriend00, I continued to work at it as you mentioned you got it to work, and I got it to work also. My problem was I was following the pattern outlined in this answer:

https://stackoverflow.com/a/17676794/5988923

The issue is the .on('error') and .on('finish') were registered after the call to pipe. I just changed it to register the events immediately after creating the write stream. Now it all works.

Thanks!

Agendum
  • 1,697
  • 1
  • 18
  • 36