Introduction
The tutorial will focus on building a basic web server using the JavaScript programming language, the Node.js runtime environment, and the Express.js framework.
Prerequisites
To follow this tutorial, you will need:
- A computer with a recent version of Windows, macOS, or Linux.
- Node.js and npm (Node Package Manager) installed on your computer. You can download Node.js and npm from the Node.js website.
Creating a new project
Create a new folder on your computer where you will host your project. Open a terminal or command prompt and navigate to that folder.
Once in the project folder, initialize a new Node.js project using npm. You can do this by running the following command in the terminal:
npm init -y
This command will create a new package.json
file in your project folder.
Installing Express.js
Now that you have a Node.js project, you can install Express.js. To do this, run the following command in the terminal:
npm install express
This command will install Express.js and add it as a dependency in your package.json
file.
Creating the web server
Create a new file called server.js
in your project folder. Open this file in a text editor and enter the following JavaScript code:
//Import the express module
const express = require('express');
//Create a new express application
const app = express();
//Define a route for the root path (/)
app.get('/', (req, res) => {
res.send('Hello, World!');
});
//Start the server on port 3000
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Starting the web server
You are now ready to start your web server. To do that, run the following command in the terminal:
node server.js
This command will start your web server on port 3000.
Open a web browser and visit http://localhost:3000
. You should see your "Hello, World!" displayed on the page.
Conclusion
Congratulations! You have just created and successfully started your first web server using Node.js and Express.js. From here, you can start further exploring the capabilities of Node.js and Express.js to develop more complex web applications.