How to create a simple http server in node.js

Node.js is an open source, cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux and FreeBSD.

Node.js provides an event-driven architecture and a non-blocking I/O API that optimizes an application's throughput and scalability. These technologies are commonly used for real-time applications.

Node.js uses the Google V8 JavaScript engine to execute code, and a large percentage of the basic modules are written in JavaScript. Node.js contains a built-in library to allow applications to act as a Web server without software such as Apache HTTP Server or IIS.

Start by creating a new file named “app.js”. Insert the following code into the file and save it.

var http = require("http");
var app = http.createServer(function(request, response) {  
    response.writeHead(200, {
        "Content-Type": "text/html"
    response.write("<!DOCTYPE "
        html ">");  
    response.write("<title>Hello Node Server Page</title>");  
    response.write("Hello World!");  
console.log("Server is listening");

To start the server, type the command shown below. If everything works properly, you will see a message that the server is listening. Note that the example server attempts to bind to port 9090, the standard HTTP port. If this port is already in use, or is restricted on your machine, you will experience an error.

node app.js

No comments:

Post a Comment