25 Aug 2013

Hello World - node.js

A simple node.js application that responds with an HTML page.

Edit server.js:

var http = require("http");

http.createServer(function(req, res) {
  res.writeHead(200, {"Content-Type": "text/html"});
  var html = "<!DOCTYPE html>"
           + "<html><head>"
           + "  <meta charset='utf-8'>"
           + "  <title>Hello World</title>"
           + "</head><body>"
           + "  <h1>Hello World</h1>"
           + "  <p>Simple node.js application</p>"
           + "</body></html>";

console.log("Server listening on port 8080");

The node instance listens on port 8080. The content type of the response is set using the Content-Type header property.

Start the server from the terminal:

$ node server.js
Server listening on port 8080

Then test in your browser:

Hello World
Simple node.js application

You may be interested in the Express equivalent.