Node.js has become one of the most popular tools for building server-side applications due to its event-driven, non-blocking architecture. In this guide, we will learn how to create a simple web server using Node.js.
Before you start, make sure you have the following installed:
Initialize a Node.js Project
First of all, create a new directory for your project and navigate into it:
$ mkdir simple-node-server
$ cd simple-node-server
Create the Web Server
Node.js provides a built-in http
module, which allows us to create a web server easily. We’ll use this to create our server.
Create a new file called server.js
:
const http = require('http');
// Define the hostname and port
const hostname = '127.0.0.1'; // localhost
const port = 3000;
// Create the server
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status and Content type
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
// Listen to the port and hostname
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Now start the server by running the command below.
$ node server.js
You can now access your brand new web server using a web browser by typing the URL http://127.0.0.1/
Obviously this is just a web server in its simplest form. But you can make it more advanced according to your requirement.
Leave a Reply