Introduction
Node.js is a powerful platform for building scalable server-side applications. In this documentation, we will walk through the process of creating a simple web server using Node.js. We'll cover the necessary steps to set up the server, handle HTTP requests, and provide a coding example with explanations.
Prerequisites
Before we begin, ensure you have Node.js installed on your machine. You can download the latest version from the official Node.js website (https://nodejs.org).
Step 1: Initializing the Project
- Create a new folder for your project and navigate to it using the command line.
- Run the following command to initialize a new Node.js project and create a
package.json
file:
csharpnpm init -y
Step 2: Installing Dependencies
- To create a web server, we'll use the built-in
http
module in Node.js. There is no need to install any additional packages for this. - If you wish to use any third-party packages or frameworks for advanced functionalities, you can install them using npm.
Step 3: Creating the Web Server
- Create a new file named
server.js
in your project folder. - Open
server.js
and add the following code:
javascriptconst 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!');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation
- We import the built-in
http
module to work with HTTP functionality in Node.js. - We define the
hostname
andport
variables to specify where the server will be accessible. - The
http.createServer()
method creates a new HTTP server instance. It takes a callback function withreq
(request) andres
(response) as parameters. - In our example, the server responds to all incoming requests with a "Hello, World!" message.
- The
server.listen()
method starts the server and makes it listen for incoming requests on the specifiedport
andhostname
. - When the server starts, it prints a message to the console.
Step 4: Running the Server
- Save the
server.js
file. - In the command line, run the following command to start the server:
node server.js
- Open a web browser and navigate to
http://127.0.0.1:3000/
. You should see the "Hello, World!" message displayed in the browser.
Conclusion
Congratulations! You have successfully created a basic web server using Node.js. From here, you can expand your server's functionality by handling different types of HTTP requests, serving HTML pages, interacting with databases, and more. Happy coding!
0 Comments