Running Nodejs Program

Once the NodeJS installed you can run a first hello world program to test NodeJS development environment.

Create a hello.js script and use a simple console.log  function that prints a message to a screen.

console.log("Hello world using Node.js");

Save the hello.js script and run it by passing a file name hello.js to a node interpreter as shown below.

C:\User\manoj\Desktop>

Output

The output of the script hello.js is

Hello world using Node.js

The web server in Nodejs

In this example, you will create a simple web server using nodejs to server a client request. To create a webserver you will use a node http module.

Create an app.js file containing the following code:

app.js

const http = require('http');
​
const hostname = '127.0.0.1';
const port = 8000;
​
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    user = {
        username: "Anonymous",
        message: "Greeting from nodejs"
​
    }
​
    JSON.stringify(user)
​
    res.end(JSON.stringify(user))
});
​
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Run app.js

C:\User\manoj\Desktop>node app.js 

The web server is listening on port no 8000 as shown above. click on a link http://127.0.0.1:8000/,.

On clicking to http://127.0.0.1:8000 a browser will opened and a GET request will be sent to a server, then server will respond a browser with a response as shown below.

Serving page using Nodejs web server

Leave a Reply

Your email address will not be published. Required fields are marked *