Creating my First NodeJS Server


JavaScript was the language of the web browser. It made our websites interactive, dynamic, and user-friendly. But its role was clear: it handled the front-end, or client-side. For the back-end—the server, database, and core application logic—developers turned to other languages like PHP, Java, or Python.
Node.js is a technology that completely changed the game. Node.js is not a new language or a framework. It is a runtime environment that allows you to run JavaScript code on the server. It took JavaScript from being a browser-only tool to a powerful, general-purpose language capable of building the entire back-end of a web application.
Setting Up Your First Node.js App
Ready to get your hands dirty? Let's build a simple "Hello World" web server.
Step 1: Install Node.js
First, you need to install Node.js on your computer.
Go to the official Node.js website: https://nodejs.org/
Download the LTS (Long Term Support) version for your operating system (Windows, macOS, or Linux). LTS is recommended for most users because it’s the most stable.
Run the installer and follow the on-screen instructions.
To verify the installation, open your terminal or command prompt and run these two commands:
Bash
node -v
npm -v
If the installation was successful, you'll see the version numbers for Node.js and npm (Node Package Manager, which is installed automatically with Node.js).
Step 2: Write Your "Hello World" Server
Now, let's write the code.
Create a new folder for your project (e.g.,
my-node-app
).Inside that folder, create a new file named
app.js
.Open
app.js
in your favorite code editor and add the following code:const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; // Create the server const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); // Send the response body "Hello World" res.end('Hello World\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Step 3: Run Your Server
It's time to bring your server to life!
Open your terminal or command prompt.
Navigate to the folder where you saved
app.js
(e.g.,cd my-node-app
).Run the following command:
Bash
node app.js
You should see the message: Server running at
http://127.0.0.1:3000/
.
- Now, open your web browser and go to that address. You'll see your "Hello World" message!
Node.js breaks the traditional boundaries of web development, bringing the power and familiarity of JavaScript directly to the server. Its clever non-blocking architecture is the key to building fast, scalable, and efficient applications.
Your "Hello, World!" server is just the beginning. The true power of Node.js is unlocked when you explore its massive ecosystem through npm (Node Package Manager).
Subscribe to my newsletter
Read articles from Deepansh Vishwakarma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
