Introduction
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. Built on Chrome's V8 JavaScript engine, Node.js allows developers to use JavaScript for server-side scripting, enabling the creation of dynamic web page content before the page is sent to the user's web browser. This tutorial will guide you through the initial steps of setting up Node.js on your system and creating a simple server.
Prerequisites
- A basic understanding of JavaScript and web development concepts.
- A text editor installed, such as Visual Studio Code, Atom, or Sublime Text.
- Access to a command-line interface (Terminal on macOS/Linux or Command Prompt/PowerShell on Windows).
Step 1: Installing Node.js
- Visit the Official Node.js Website:
- Navigate to nodejs.org.
- Download the Installer:
- You will see two versions available:
- LTS (Long Term Support): Recommended for most users seeking stability.
- Current: Contains the latest features but may have more frequent updates.
- Click on the appropriate installer for your operating system (Windows, macOS, or Linux).
- You will see two versions available:
- Run the Installer:
- Locate the downloaded installer file and double-click to run it.
- Follow the installation prompts:
- Accept the license agreement.
- Select the destination folder (default is recommended).
- Ensure that the option to install npm (Node Package Manager) is checked.
- Complete the installation process.
- Verify the Installation:
- Open your command-line interface.
- Type
node -v
and press Enter. You should see the Node.js version number displayed. - Type
npm -v
to verify that npm was installed successfully.
Step 2: Setting Up Your First Node.js Server
- Create a Project Directory:
- Open your command-line interface.
- Navigate to the directory where you want to create your project.
- Run
mkdir my-node-app
to create a new directory namedmy-node-app
. - Navigate into the directory with
cd my-node-app
.
- Initialize a New Node.js Project:
- Run
npm init
and press Enter. - You'll be prompted with several questions:
- Package name: Press Enter to accept the default.
- Version: Press Enter to accept the default.
- Description: Enter a brief description or leave blank.
- Entry point: Type
server.js
or accept the defaultindex.js
. - Continue pressing Enter to accept defaults or provide specific values.
- At the end, type
yes
to confirm.
- This will generate a
package.json
file in your project directory.
- Run
- Create the Server File:
- Open your text editor.
- Create a new file and save it as
server.js
in your project directory.
- Add the Server Code:
- In
server.js
, add the following code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
- This script creates a basic HTTP server that listens on port 3000 and responds with "Hello, World!"
- In
- Run the Server:
- Save the
server.js
file. - In your command-line interface, ensure you're in the
my-node-app
directory. - Type
node server.js
and press Enter. - You should see the message:
Server running at http://127.0.0.1:3000/
.
- Save the
- Test Your Server:
- Open a web browser.
- Navigate to http://localhost:3000.
- You should see the message "Hello, World!" displayed.
Step 3: Exploring Node.js Modules
- Understand Built-in Modules:
- Node.js comes with several built-in modules like
fs
for file system operations,path
for handling file paths, andos
for operating system-related utility methods.
- Node.js comes with several built-in modules like
- Using the
fs
Module:
- In your
server.js
, add the following code to read a file:
const fs = require('fs');
fs.readFile('message.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
- Create a
message.txt
file with some content in your project directory. - Run
node server.js
to see the file content logged in the console.
- In your
Step 4: Installing External Modules
- Install Express.js:
- Express.js is a popular web framework for Node.js that simplifies server creation.
- In your command-line interface, stop the server by pressing
Ctrl + C
. - Run
npm install express
to install Express.js. - You'll notice that a
node_modules
folder and apackage-lock.json
file are added to your project.
- Create a Server with Express.js:
- Replace the content of
server.js
with the following code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World with Express!');
});
app.listen(port, () => {
console.log(`Express server running at http://localhost:${port}/`);
});
- This code sets up a simple Express server that responds to GET requests at the root URL.
- Replace the content of
- Run the Express Server:
- Save the updated
server.js
file. - In the command-line interface, run
node server.js
. - Visit http://localhost:3000 in your web browser. You should see "Hello, World with Express!" displayed.
- Save the updated
Step 5: Handling Routes and Middleware (Optional)
- Add Additional Routes:
- In
server.js
, add the following route handlers:
app.get('/about', (req, res) => {
res.send('About Page');
});
app.get('/contact', (req, res) => {
res.send('Contact Page');
});
- Restart your server and visit
http://localhost:3000/about
andhttp://localhost:3000/contact
.
- In
- Use Middleware:
- Add middleware to serve static files:
app.use(express.static('public'));
- Create a folder named
public
in your project directory. - Add a file
public/style.css
with some CSS styles. - Link the CSS file in your HTML responses (requires modifying route handlers to send HTML).
- Add middleware to serve static files:
Conclusion
Congratulations! You've set up your first Node.js server and learned how to enhance it using Express.js. You've also explored how to use built-in modules and install external packages using npm. From here, you can delve deeper into Node.js and Express to build more complex and feature-rich web applications. Consider learning about routing, middleware, templating engines, working with databases, and deploying your application to a hosting service.
Additional Resources