Skip to content

Instantly share code, notes, and snippets.

@pgte
Last active January 17, 2021 09:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgte/cd559940dd1ee1d81cc1 to your computer and use it in GitHub Desktop.
Save pgte/cd559940dd1ee1d81cc1 to your computer and use it in GitHub Desktop.
node request and response life cycle
var https = require('https');
var querystring = require('querystring');
var events = ['socket', 'connection', 'response', 'data', 'end', 'close', 'finish'];
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 443,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('res data: %j', chunk.substring(0, 30) + '...');
});
observe('response', res);
});
observe('request', req);
req.end(postData);
function observe(name, emitter) {
events.forEach(function(event) {
emitter.on(event, function() {
console.log('%s - %s', name, event);
});
});
}
request - socket
request - finish
request - response
res data: "<!DOCTYPE html>\n<html lang=en>..."
response - data
res data: ":url(//www.google.com/images/b..."
response - data
res data: "o_color_150x54dp.png) no-repea..."
response - data
response - end
request - close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment