Node.js Http Example


Similarly to the fs module, Node.js core contains a http module which can be used to act as a HTTP client or server. In the next lab you will be creating a HTTP server, but for now, we will focus on creating a simple wget command to download a file.

Import the http module up top next to where you imported fs:

var http = require('http');

Now, we will use http.get(url, callback) to make a HTTP GET request and download the results to the file system.

Example 1: Read index.html file from current location. Let's use this template engine to parse the content of our index.html file.

var fs = require('fs');
var http = require('http');
var server = http.createServer(function (req, res) {
	res.statusCode = 200;
	fs.readFile('index.html', function (err, data) {
	if (!err) {
		res.write(templateEngine(data.toString(), {
			name: 'Ryan Dahl',
			node: process.versions.node,
			v8: process.versions.v8,
			time: new Date(),
			url: req.url
		}));
		res.end();
		}
	})
});
server.listen(3000)

Now try this in the browser. You'll notice that the output is the same. Let's update index.html to take advantage of our template engine.

<html>
	<head>
		<title>My Node.js server</title>
	</head>
  <body>
	<h1>Hello {name}!</h1>
	<ul>
		<li>Node Version: {node}</li>
		<li>V8 Version: {v8}</li>
		<li>URL: {url}</li>
		<li>Time: {time}</li>
	</ul>
  </body>
</html>

Example 2: URL creation

var http = require("http");
var url = require('url');
var fs = require('fs');

var server = http.createServer(function(request, response){
    console.log('Connection');
    var path = url.parse(request.url).pathname;
 console.log(path);
    switch(path){
        case '/':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('hello world');
            break;
        case '/socket.html':
    response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('Inside hello world');
            fs.readFile(__dirname + path, function(error, data){
                if (error){
                    response.writeHead(404);
                    response.write("opps this doesn't exist - 403");
                }
                else{
                    response.writeHead(200, {"Content-Type": "text/html"});
                    response.write(data, "utf8");
                }
            });
            break;
        default:
            response.writeHead(404);
            response.write("opps this doesn't exist - 405");
            break;
    }
    response.end();
}).listen(8124);


console.log('Server running at http://127.0.0.1:8124/');

We have two differnt urls which can access by http://127.0.0.1:8124/. One is defualt which is http://127.0.0.1:8124/, and another one is http://127.0.0.1:8124/socket.html

The callback function function (req, res) {} passed into the createServer call will be invoked with every new request to our server. This callback is passed two arguments, the request (a readable stream) and the response (a writable stream).

Our new server is not yet bound to any port, and therefore cannot accept incoming connections. In order to bind to a port, call the server.listen(port) function.