Open In App

How to create a simple server in Node.js that display Hello World ?

Last Updated : 01 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

A Server is a piece of computer hardware or software that provides functionality for other programs or devices, called clients. This architecture is called the client-server model. Node is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript.

In the following example, we will create a simple server in Node.js that returns Hello World using an express server.

Create NodeJS Application: Initialize the NodeJS application using the following command:

npm init

Module Installation: Install the express module which is a web framework for NodeJS using the following command.

npm install express

Implementation: Create an app.js file and write down the following code in it.

app.js




// Require would make available the
// express package to be used in
// our code
const express = require("express");
  
// Creates an express object
const app = express();
  
// It listens to HTTP get request. 
// Here it listens to the root i.e '/'
app.get("/", (req, res) => {
  
  // Using send function we send
  // response to the client
  // Here we are sending html
  res.send("<h1> Hello World </h1>");
});
  
// It configures the system to listen
// to port 3000. Any number can be 
// given instead of 3000, the only
// condition is that no other server
// should be running at that port
app.listen(3000, () => {
  
  // Print in the console when the
  // servers starts to listen on 3000
  console.log("Listening to port 3000");
});


Step to run the application: Run the app.js file using the following command.

node app.js

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

output

So this is how you can set up the server and achieve the task. If you want to return anything else then pass that argument in res.send() of the app.get() function instead of “Hello World”.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads