
Build Your First Server In Node.JS
Hey Devs!
Ready to start developing your own system? Today we will learn how to get the right tools and npm setup.
Table of Contents |
---|
What is Node.js? |
Node js and npm Installation |
Writing First Program in Node js |
Installing packages with npm |
Setting up a http server |
Additional Tips |
Introduction
Node.js is one of the most powerful and popular JavaScript runtime environments available today. It allows developers to build scalable, high-performance applications not just for web front-ends but also for backend services, APIs, and more. Whether you're just starting out in programming or looking to refresh your understanding of Node.js fundamentals, this guide will walk you through setting up Node.js on your local machine and writing your very first Node.js program.
What is Node.js?
At its core, Node.js is an open-source, cross-platform JavaScript runtime environment. This means it allows you to run JavaScript code outside of a web browser, directly on your computer. It's built on Chrome's V8 JavaScript engine, which is known for its speed and efficiency, making Node.js particularly good for building fast and scalable network applications.
Key Benefits of Node.js:
- Asynchronous and Event-Driven: Node.js handles many operations at once without waiting for each one to finish, making it very efficient for tasks like handling multiple user requests simultaneously.
- Single-Threaded but Highly Scalable: While it uses a single thread for execution, its event-driven architecture allows it to handle a large number of concurrent connections efficiently.
- Uses JavaScript Across the Stack: If you know JavaScript, you can use it for both the front-end (what users see) and the back-end (server-side logic), simplifying development.
- Massive Ecosystem (npm): Node.js has a vast collection of open-source packages and libraries available through npm (Node Package Manager), which can save you a lot of time and effort in development.
Prerequisites
Before you begin, make sure you have the following:
-
A basic understanding of programming concepts like variables and functions.
If you don't know these you can use Navic the AI bot at the right bottom corner or can google the basic definitions. It's not necessary you know them but having a basic knowledge will help you practice and understand better.
-
A code editor: A text editor designed for writing code is highly recommended. Visual Studio Code (VS Code) is a popular and excellent choice.
-
An internet connection: You'll need it to download Node.js and any necessary packages.
Step 1: Installing Node.js
The first step is to get Node.js installed on your computer.
For Windows & macOS:
- Go to the official Node.js website: https://nodejs.org
You'll see two main download options: "LTS" (Long-Term Support) and "Current."
Note: Always choose the LTS version. LTS versions are more stable and recommended for most users.
- Download the installer file for your operating system.
- Once downloaded, run the installer.
- Follow the on-screen prompts. During the installation, ensure that npm (Node Package Manager) is selected to be installed along with Node.js. It usually is by default.
For Linux (Ubuntu/Debian):
-
Open your terminal (command line interface) and run the following commands. These commands will update your package lists and then install Node.js and npm:
sudo apt update sudo apt install nodejs npm
Verify Installation:
After the installation is complete, open a new terminal or command prompt window (or restart your existing one). Type the following commands to check if Node.js and npm were installed correctly:
node -v
This command should display the installed Node.js version (e.g., v20.x.x).
npm -v
This command should display the installed npm version (e.g., 10.x.x).
If you see version numbers, congratulations! Node.js is successfully installed.
Step 2: Setting Up Your First Node.js Project
Now that Node.js is installed, let's create a simple project to organize our code.
Create a project folder:
Open your terminal or command prompt and navigate to a location where you want to create your project. Then, use the following commands to create a new directory (folder) and move into it:
mkdir my-node-app
cd my-node-app
Initialize the project with npm:
Inside your my-node-app
folder, run the following command:
npm init -y
The npm init -y
command creates a file named package.json
in your project folder. This file is crucial for Node.js projects as it stores metadata about your project (like its name and version) and, more importantly, keeps track of all the external packages (dependencies) your project relies on. The -y
flag tells npm to use default values for all the prompts, making the process quicker.
Step 3: Writing Your First Node.js Script
Let's write a simple JavaScript file that Node.js can execute.
Create a file:
Inside your my-node-app
folder, create a new file and name it app.js
. You can do this through your code editor or by using a terminal command (e.g., touch app.js
on Linux/macOS or notepad app.js
on Windows).
Add code to app.js:
Open app.js
in your code editor and add the following line of JavaScript code:
// app.js
console.log("Hello from Node.js!");
The console.log()
function is a standard JavaScript function that prints text to the console.
Run the script:
Go back to your terminal, ensuring you are still inside the my-node-app
directory. Then, execute your script using the node
command:
node app.js
You should see the following output in your terminal:
Hello from Node.js!
Step 4: Installing and Using an npm Package
One of Node.js's greatest strengths is its massive ecosystem of packages available through npm. Let's install a common package called chalk
, which allows you to add colored text to your terminal output.
Install the chalk package:
In your my-node-app
directory in the terminal, run:
npm install chalk
This command downloads the chalk
package and saves it in a node_modules
folder within your project. It also adds chalk
as a dependency to your package.json
file.
Update your app.js:
Open app.js
again and modify its content to use the chalk
package:
const chalk = require('chalk'); // This line "imports" the chalk package
console.log(chalk.green('Success! Node.js is working.'));
require('chalk')
is how you bring in (or "import") external Node.js packages into your script.chalk.green()
is a function provided by thechalk
package that makes the text inside it appear green in the terminal.
Run it again:
node app.js
Now, your terminal should display the text "Success! Node.js is working." in green color!
Step 5: Building a Simple Web Server
Node.js is excellent for building web servers. Let's create a very basic HTTP server.
Create a new file:
In your my-node-app
folder, create a new file named server.js
.
Add server code to server.js:
// server.js
const http = require('http'); // Node.js's built-in HTTP module
// Create an HTTP server
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello from the Node.js server!\n');
});
// Make the server listen on port 3000
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Explanation:
require('http')
loads Node.js's built-in HTTP module.http.createServer()
creates an HTTP server object.req
(request) contains information about the incoming request.res
(response) sends data back to the client.res.statusCode = 200;
sets the HTTP status code.res.setHeader('Content-Type', 'text/plain');
tells the browser that the response is plain text.res.end()
sends the content and ends the response.server.listen(3000, ...)
starts the server on port 3000.
Start the server:
node server.js
You should see:
Server running at http://localhost:3000/
Open your browser and go to http://localhost:3000
. You should see:
Hello from the Node.js server!
Press Ctrl+C
in your terminal to stop the server.
Useful Tips
nodemon for Auto-Reloading:
npm install -g nodemon
Run server with:
nodemon server.js
Using node --watch (Node.js 18+):
node --watch server.js
Uninstalling a Package:
npm uninstall <package-name>
(e.g., npm uninstall chalk
)
Updating All Packages:
npm update
Beginner Tips
- Read Error Messages Carefully: They usually contain valuable clues.
- Use console.log() for Debugging: Helps track variable values and code flow.
- Understand Asynchronous JavaScript: Learn Callbacks, Promises, async/await.
- Explore npmjs.com: Search for useful packages.
- Don’t Be Afraid to Google: Most issues have been faced (and solved) before.
- Version Control (Git): Learn Git and GitHub early for project tracking.
Conclusion
Setting up Node.js locally is a straightforward process that unlocks a world of possibilities in backend development and full-stack web development. With a solid understanding of the setup steps and a few lines of code, you are now equipped to dive deeper and start building more complex, real-world applications.
Have fun coding with Node.js!
Enjoy the content here?
Sign up on our platform or join our WhatsApp channel here to get more hands-on guides like this, delivered regularly.
See you in the next blog. Until then, keep practicing and happy learning!
4 Reactions
0 Bookmarks