Home > Software design >  When should I use 'open' event in Node.js?
When should I use 'open' event in Node.js?

Time:02-21

I'm learning Node.js and while touching events and streams topic I encountered this example:

const http = require('http');
const fs = require('fs');

http
  .createServer((req, res) => {
    const fileStream = fs.createReadStream('./some-data.txt', 'utf8');
    
    fileStream.on('open', () => {
      fileStream.pipe(res);
    });

    fileStream.on('error', (err) => {
      res.end(err);
    });
  })
  .listen(5000);

While I understand the logic behind this code (server transfers some big data in chunks with the help of streams), I don't understand the benefit of using 'open' event. Same code, where I just pipe data from read stream into write one (res object) right after creating fileStream without listening to 'open', produces exactly same result. What is the difference and in which cases should I listen to 'open'?

const http = require('http');
const fs = require('fs');

http
  .createServer((req, res) => {
    const fileStream = fs.createReadStream('./some-data.txt', 'utf8');

    fileStream.pipe(res);

    fileStream.on('error', (err) => {
      res.end(err);
    });
  })
  .listen(5000);

CodePudding user response:

In this particular case, it does not really make any difference if you use the open event or not. If the file does not exist, the error event will be emitted anyway and you will send it via res.end(err.message) (not that res.end(err) fails because the err is an object).

The open event tells us that the stream is open so that we can handle that in the code.

  • Related