I'm trying to understand the event loop in Node.js, and how event programming works. Given that my module exports a function that returns something in the callback of data event:
var http = require('http');
module.exports.send = function send(message) {
http.request({ hostname: 'google.com' }, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
return chunk;
}
});
};
How this can work?
If I understand correctly, http.request is an asynchronous operation, that means:
http.request is performed;data event is emitted), maybe after minutes, send function returns the data. Not before.Thus result should be undefined, but actually is not:
var send = require('mymodule').send;
var result = send({});
console.log(result);
The main thing to think about is what is calling the data callback. In this case, that function is called from a random place inside of Node, so when you return chunk;, you are returning that chunk to that part of Node, you are not returning it back to your own code, as that has already finished running.
If you want to actually get that data, you need to pass a callback of your own into send that will be triggered when data comes back.
module.exports.send = function send(message, callback) {
http.request({ hostname: 'google.com' }, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
callback(chunk);
});
});
};
then called like this:
var mod = require('...');
mod.send('message data', function(result){
console.log(result);
});
Keep in mind that the data event can be emitted any number of times, so you will want to collect all of the chunk values and then call your callback once the end event fires.