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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With