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.js in your preferred text editor and add the following code to create a basic HTTP server.

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:

node app.js

Output:

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

Explanation

Tip

Code breakdown step by step

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..");
  • Step 1: Import Node.js core module (http)
  • Step 2: Create the HTTP server using http.createServer(...)
  • Step 3: Handle incoming requests and send a response (res.write("Hello World!"); res.end();)
  • Step 4: Listen for incoming connections on port 5000 (server.listen(5000))
  • Step 5: Print a message in the console verifying the server is active
← Back