Devesh Kumar No comments

Node js First application

There is one module we need to use for creating node.js first sample application. which can receive the client's request and respond according to it.

Creating Node.js Application


Step 1 - Import Required Module


We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows −

var http = require("http");

Step 2 - Create a Server


We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 3000 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return "Welcome to node app".

const http = require("http");

const handler = (req, res) => {
    // Send the HTTP header 
    // HTTP Status: 200 : OK
    // Content Type: text/plain
    res.writeHead(200, { "content-type": "text/plain" });

    // Send the response body as "Welcome to node app"
    res.end("Welcome to node app");
}

const server = http.createServer(handler);
server.listen(3000, () => {
    // Console will print the message
    console.log("Server Started on port 3000");
});

The above code is enough to create an HTTP server that listens, i.e., waits for a request over 3000 port on the local machine.

Step 3 - Testing Request & Response

Let's put steps 1 and 2 together in a file called index.js and start our HTTP server as shown below −

Now execute the index.js to start the server as follows −

$ node index.js

Verify the Output. The server has started.

Server running at http://127.0.0.1:3000/ or http://localhost:3000/

Comments (0)

Post a Comment

Cancel