Reputation: 13
it might be a stupid question already but my purpose of this is to return an object called user where I can then use properly. http node.js documentation is full of console.log but nothing mentioned about returning objects. this is my code (which is from the standard documentation) where I also tried to assign the user or return it in the end method but it always return false.
var options= {
host : 'localhost',
port : 3000,
path : '/users?userName=Rosella.OKon56', // the rest of the url with parameters if needed
method : 'GET' // do GET
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
//console.log(str);
});
}
var req = http.request(options, callback);
req.end();
Upvotes: 0
Views: 4026
Reputation: 1075527
Return something that you can then parse into an object structure. For instance, if you return JSON, you can use JSON.parse
to parse it.
where I also tried to assign the user or return it in the end method but it always return false
If you want to do something with the parsed result, you would call a function with the result from within your end
callback, like this:
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
doSomethingWithUserObject(JSON.parse(str));
});
}
Side note: Your code is falling prey to The Horror of Implicit Globals; you need to declare your callback
variable. You're also relying on Automatic Semicolon Insertion (you need a ;
after your function expression, since it's not a declaration), which I don't recommend doing, but some people like.
Upvotes: 1