3

I am completely new to Node.js, hence I couldn't understand how does this function work from the documentation. Can someone please provide me with a simple explanation to the on() method, considering me a beginner. Thank You.

const https = require('https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();
Tanish Sharma
  • 47
  • 1
  • 6

1 Answers1

12

res is a readstream of the incoming data from the response. Streams in node.js are derived from EventEmitter objects - they have a number of events that you can listen to.

The .on() method on a stream is how you register a listener for a particular event.

res.on('data', ...) is how you register a listener for the data event and the data event is the primary way that you receive data from the incoming stream. This listener will be called one or more times with chunks of arriving data.

Another important event is the end event which tells you that you've reached the end of the data - there is no more data.

You can see the various events and methods on a readStream here.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • What I do not understand here is, since we are using Javascript, why aren't we doing res.addEventListener? Instead we do res.on to listen for the 'data' event. Why? – Heshan Kumarasinghe Jul 14 '21 at 09:12
  • 2
    @HeshanKumarasinghe - `res.on()` is an alias for `res.addListener()`. They are the same thing. See [What is the difference between addListener and on](https://stackoverflow.com/questions/29861608/what-is-the-difference-between-addlistenerevent-listener-and-onevent-listen/29861649#29861649) for further explanation. – jfriend00 Jul 14 '21 at 16:15