How To Create Node Server
javascriptNodeserver
Sep 10, 2022

Node.js is a JavaScript runtime that allows you to build server-side applications with JavaScript. In this guide, we'll walk you through the steps to create a simple HTTP server using Node.js.

Step 1: Set Up the Project

First, open your terminal and create a new directory for your Node.js project. You can do this by running the following command:


mkdir node-server
cd node-server

This creates a new directory called node-server and navigates into it.

Step 2: Initialize the Project (Optional)

Before creating the server, it's a good idea to initialize a package.json file to keep track of your dependencies. Run this command to generate a package.json file:


npm init -y

This will create a default package.json file in your project directory, which you can later edit to add dependencies.

Step 3: Create the app.js File

Next, you'll create a new JavaScript file where you'll write the code for your Node.js server. In your terminal, run:


touch app.js

This command will create a new file named app.js.

Step 4: Write the Server Code

Open app.jsin your preferred text editor and add the following code to create a basic HTTP server.

app.js

var http = require("http");
var server = http.createServer(function (req, res) {
res.write("Hello World!");
res.end();
});
server.listen(5000);
console.log("Node.js web server at port 5000 is running..");

To run this command app.js


node app.js

output:

console

Node.js web server at port 5000 is running..

Explanation

Tip

For better view use large screen - Click every step

👆 step 1: Import Node.js core module

step 2: creating server

step 3: handle incomming requests here..

step 4: listen for any incoming requests

step 5: console log

Output

app.js

var http = require("http");
var server = http.createServer(function (req, res) {
res.write("Hello World!");
res.end();
});
server.listen(5000);
console.log("Node.js web server at port 5000 is running..");

← Back

2022 © Rahat Hosen