Install Node.js
Before you begin, you need to have Node.js installed on your system. You can install it using several methods:
Download from nodejs.org
Visit nodejs.org and download the LTS version for your operating system. The LTS (Long Term Support) version is recommended for most users as it provides stability and long-term support.
Using a version manager (Recommended)
For more flexibility, use a version manager like nvm or n: macOS/Linux (nvm)
Windows (nvm-windows)
# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# Install Node.js LTS
nvm install --lts
# Use the installed version
nvm use --lts
Verify installation
Confirm Node.js is installed correctly: node --version
npm --version
You should see version numbers for both Node.js and npm.
Create your first HTTP server
Let’s build a simple HTTP server that responds to requests. This is one of the most common use cases for Node.js.
Create a project directory
mkdir my-first-node-app
cd my-first-node-app
Create server.js file
Create a new file called server.js with the following code: const http = require ( 'http' );
// Create an HTTP server
const server = http . createServer (( req , res ) => {
// Set response headers
res . writeHead ( 200 , {
'Content-Type' : 'text/plain' ,
'Content-Length' : '13'
});
// Send response body
res . end ( 'Hello, World!' );
});
// Server listens on port 3000
const PORT = 3000 ;
server . listen ( PORT , () => {
console . log ( `Server running at http://localhost: ${ PORT } /` );
});
This example uses the built-in http module from Node.js. No additional dependencies are required.
Understanding the code
Let’s break down what this code does:
http.createServer(): Creates a new HTTP server instance
Request handler function (req, res): Called for each incoming request
res.writeHead(): Sets the HTTP status code and headers
res.end(): Sends the response body and ends the response
server.listen(): Starts the server on the specified port
Run the server
Start your server with a single command:
You should see the output:
Server running at http://localhost:3000/
Your server is now running! Keep the terminal window open to keep the server active.
Test your server
There are multiple ways to test your new server:
cURL
Browser
Node.js HTTP Client
curl http://localhost:3000
# Output: Hello, World!
Enhance your server
Let’s make the server more functional by handling different routes and HTTP methods:
const http = require ( 'http' );
const server = http . createServer (( req , res ) => {
const { method , url } = req ;
// Set default headers
res . setHeader ( 'Content-Type' , 'application/json' );
// Handle different routes
if ( url === '/' && method === 'GET' ) {
res . writeHead ( 200 );
res . end ( JSON . stringify ({ message: 'Welcome to the API' }));
}
else if ( url === '/api/status' && method === 'GET' ) {
res . writeHead ( 200 );
res . end ( JSON . stringify ({
status: 'OK' ,
timestamp: new Date (). toISOString (),
uptime: process . uptime ()
}));
}
else if ( url === '/api/user' && method === 'POST' ) {
let body = '' ;
req . on ( 'data' , chunk => {
body += chunk . toString ();
});
req . on ( 'end' , () => {
try {
const data = JSON . parse ( body );
res . writeHead ( 201 );
res . end ( JSON . stringify ({
message: 'User created' ,
user: data
}));
} catch ( error ) {
res . writeHead ( 400 );
res . end ( JSON . stringify ({ error: 'Invalid JSON' }));
}
});
}
else {
// 404 Not Found
res . writeHead ( 404 );
res . end ( JSON . stringify ({ error: 'Route not found' }));
}
});
const PORT = process . env . PORT || 3000 ;
server . listen ( PORT , () => {
console . log ( `Server running at http://localhost: ${ PORT } /` );
console . log ( 'Available routes:' );
console . log ( ' GET /' );
console . log ( ' GET /api/status' );
console . log ( ' POST /api/user' );
});
This enhanced version demonstrates routing, different HTTP methods, JSON handling, and environment variables.
Test the enhanced server
Try these different endpoints:
GET /
GET /api/status
POST /api/user
curl http://localhost:3000/
# {"message":"Welcome to the API"}
Working with packages
Node.js has a rich ecosystem of packages available through npm (Node Package Manager).
Initialize your project
This creates a package.json file to manage your project dependencies.
Install a package
Let’s install Express, a popular web framework:
Create an Express server
const express = require ( 'express' );
const app = express ();
// Middleware to parse JSON
app . use ( express . json ());
// Routes
app . get ( '/' , ( req , res ) => {
res . json ({ message: 'Welcome to Express!' });
});
app . get ( '/api/users' , ( req , res ) => {
res . json ([
{ id: 1 , name: 'Alice' },
{ id: 2 , name: 'Bob' }
]);
});
app . post ( '/api/users' , ( req , res ) => {
const user = req . body ;
res . status ( 201 ). json ({ message: 'User created' , user });
});
const PORT = process . env . PORT || 3000 ;
app . listen ( PORT , () => {
console . log ( `Express server running on port ${ PORT } ` );
});
Express simplifies routing, middleware, and request handling compared to the raw HTTP module.
Enhance your development experience with these tools:
Auto-restart with nodemon
# Install nodemon globally
npm install -g nodemon
# Or as a dev dependency
npm install --save-dev nodemon
# Run your server with auto-restart
nodemon server.js
Now your server automatically restarts when you save changes to your files.
Environment variables
Create a .env file for configuration:
PORT = 3000
NODE_ENV = development
DATABASE_URL = mongodb://localhost:27017/myapp
Use the dotenv package to load environment variables:
require ( 'dotenv' ). config ();
const PORT = process . env . PORT || 3000 ;
const env = process . env . NODE_ENV || 'development' ;
console . log ( `Running in ${ env } mode on port ${ PORT } ` );
Next steps
Congratulations! You’ve created your first Node.js server. Here’s what to explore next:
Installation guide Learn about different installation methods and building from source
API documentation Explore Node.js built-in modules and APIs
Best practices Learn Node.js best practices and design patterns
Deployment Deploy your Node.js application to production
Common issues
Port already in use If you see Error: listen EADDRINUSE, another process is using the port. Either:
Stop the other process
Use a different port: const PORT = 3001;
Module not found If you see Error: Cannot find module, make sure you:
Installed dependencies with npm install
Used the correct require path
Are in the correct directory
Additional resources