nodejs hello world http server and http get

1. Install node from http://nodejs.org/
2. httpServer.js,the node http server file.

var http = require('http');
var server = http.createServer(function (req, res) {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.end("Hey, this is a response from a server!\n");
});
server.listen(1212); // listening on port 1212

3. httpGet.js, the node http get file. process.argv[2] is the url passed in on the command line.

var http = require('http');
var url = process.argv[2];

http.get(url, function(response) {
    response.setEncoding('utf8');
    response.on('data', function(data) {
        console.log(data);
    });
    response.on('err', function(err){
        console.log(err);
    });
});

First, run the httpServer.js file from command line.
node httpServer.js

Second, run the httpGetServer.js file from command line.
node httpGet.js http://localhost:1212

You can also use the unix curl command or enter this url to a browser to get the same response from the httpServer.js
curl http://localhost:1212

The response you will be seeing

Hey, this is a response from a server!

Search within Codexpedia

Custom Search

Search the entire web

Custom Search