1. Setting Up Node.js
Node.js is a powerful runtime environment that allows developers to execute JavaScript on the server side. Whether you're building a small API or a full-fledged web application, setting up Node.js is the first crucial step. In this guide, we’ll walk through installing Node.js, configuring your environment, and running your first Node.js application.
2. Why Set Up Node.js?
Setting up Node.js gives you access to a robust development environment for creating fast, scalable, and efficient server-side applications. With Node.js, you can build web servers, APIs, real-time applications, and much more using a single language—JavaScript.
3. Download and Install Node.js
1. Visit the Official Node.js Website
Go to the official Node.js website. You’ll see two download options:
2. Download the Installer
Choose the appropriate version for your operating system:
3. Run the Installer
Follow the installation prompts:
4. Verify the Installation
Once installation is complete, verify that Node.js and npm are installed by opening your terminal (Command Prompt, PowerShell, or macOS Terminal) and running these commands:
node -v
This command will display the installed version of Node.js.
npm -v
This command will display the installed version of npm.
4. Create Your First Node.js Application
1. Create a New Directory
Navigate to a location where you want to create your project and run the following commands:
mkdir my-first-node-app
cd my-first-node-app
2. Initialize the Project
To create a new Node.js project, use npm to generate a package.json file by running:
npm init -y
This will create a basic package.json file with default settings.
3. Create a Simple Server
Create a new file named app.js in your project directory. Open it in your favorite text editor and add the following code:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World! This is my first Node.js app.');
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
4. Run Your Node.js Application
To start the server, run the following command in the terminal:
node app.js
You’ll see the message: Server is running on http://localhost:3000. Open your browser and go to http://localhost:3000 to see your "Hello, World!" message.
5. Managing Dependencies with npm
1. Installing a Dependency
For example, install the popular express framework:
npm install express
2. Using the Dependency
Modify app.js to use Express:
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(3000, () => {
console.log('Express server running on http://localhost:3000');
});
Run the updated code:
node app.js