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

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.

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

Example 2: URL creation

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

var server = http.createServer(function(request, response){
    var path = url.parse(request.url).pathname;
        case '/':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('hello world');
        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.write("opps this doesn't exist - 403");
                    response.writeHead(200, {"Content-Type": "text/html"});
                    response.write(data, "utf8");
            response.write("opps this doesn't exist - 405");

console.log('Server running at');

We have two differnt urls which can access by One is defualt which is, and another one is

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.