I've been trying to connect node to a web page and return the result in the same program. Here's the code I have:
var http = require('http'),
sys = require('sys'),
fs = require('fs');
var options = {
host: 'myurl.com',
port: 80,
path: '/path/to/file',
method: 'POST'
};
var myglobal = "the test";
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);
myglobal = chunk;
console.log("myglobal = " + myglobal);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
console.log("outside of http request: myglobal = " + myglobal);
Now what I want to happen is for "myglobal" to have the contents of the output of the web page "myurl.com" at the end of the program. This doesn't happen however and I can't seem to figure out how to get the contents from the "chunk" into another variable in the program. I thought the contents would be in either the "req" or "res" variable but I dumped the vars and couldn't find the output in either place. So at the end, "myglobal" still says "the test", where the "myglobal" within the http.request code has the output of "chunk". Just curious to know what it is I'm missing here. Thanks.
Darryl
No comments:
Post a Comment