How to create a simple server in Node.js that display Hello World ?
Last Updated :
01 Oct, 2021
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
const express = require( "express" );
const app = express();
app.get( "/" , (req, res) => {
res.send( "<h1> Hello World </h1>" );
});
app.listen(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
Share your thoughts in the comments
Please Login to comment...