In official doc, there is some sample code:
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
I can understand it except one part: what's on
in res.on
? What's the difference between it and addListener
?
In Node. js, you usually bind functions (using 'on' or other functions) to listen to events.
When in Node JS, one iteration of the event loop is completed. This is known as a tick. process. nextTick() taking a callback function which is executed after completing the current iteration/tick of the event loop. Phases of Event Loop in Node JS from nodejs.org.
The setImmediate function is used to execute a function right after the current event loop finishes. In simple terms, the function functionToExecute is called after all the statements in the script are executed. It is the same as calling the setTimeout function with zero delays.
libuv is a multi-platform C library that provides support for asynchronous I/O based on event loops. It supports epoll(4) , kqueue(2) , Windows IOCP, and Solaris event ports. It is primarily designed for use in Node. js but it is also used by other software projects.
As far as I'm aware, it's no different than addListener
. There is some documentation on the event here: http://nodejs.org/docs/latest/api/events.html#emitter.on Both on
and addListener
are documented under the same heading. They have the same effect;
server.on('connection', function(stream) {
console.log('someone connected!');
});
server.addListener('connection', function(stream) {
console.log('someone connected!');
});
Both on
and addListener
are aliases for the same function.
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