Q:

Node; default value if readable stream throws an error

I have the following situation, where a reading stream pipes to a writing stream:
let rs = fs.createReadStream(getSrcFileName());
let ws = fs.createWriteStream(getTrgFileName());

rs.pipe(ws);

// ...

This works just fine. Now, I want to ensure something always gets written to the file at getTrgFileName(), even when rs encounters an error. If an error occurred, I'd like the content in the output file to be 'error occurred'.
For example, currently if getSrcFileName() refers to a non-existent file the entire setup fails and nothing is written to the output file. What stream operations can I apply to generate a default value upon error?
Thanks!

A:

You can simply add the on error handler, and write to the file that way...
const fs = require('fs');

rs.on('error', (error) => {
    fs.writeFile('YourFileName.txt', 'error occurred', (err) => { 
      if (err) throw err;
        console.log('File saved, but with errors!');
    });
});

Or, if you wanted to just chain it directly to what you're already using....
const fs = require('fs');

let rs = fs.createReadStream(getSrcFileName());
let ws = fs.createWriteStream(getTrgFileName());

rs.pipe(ws)
  .on('error', (error) => {
     fs.writeFile('YourFileName.txt', 'error occurred', (err) => { 
       if (err) throw err;
       console.log('File saved, but with errors!');
     });
   });

Edit:
To continue with your writestream...
rs.pipe(ws)
  .on('error', (error) => {
     ws.write('error occurred');
   });

