Reputation: 11
This http.request code is from http://nodejs.org/docs/v0.4.7/api/http.html#http.request. How to export chunk in res.on ?
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
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);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Upvotes: 0
Views: 899
Reputation: 11656
I'm not sure what you mean by "export" but perhaps you'd like to put the contents of the response into a local text file?
Here's how you might go about doing that:
var http = require('http');
var fs = require('fs');
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
var response;
if(fs.existsSync('response.html'))
response = fs.readFileSync('response.html') + chunk;
else
response = chunk;
fs.writeFileSync('response.html', response);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Note that after each data
event is fired, we're checking for an existing file with fs.existsSync
, populating a response variable accordingly and then writing the response to a file again with fs.writeFileSync
.
This wouldn't be much use on a server, as the synchronous nature of the file reads/writes would bottleneck your traffic, but it does highlight the general concept of responding to events and concatenating chunks.
Upvotes: 1