Creating a web server in Node.js is relatively simple due to its built-in ‘http’ module. You can create an elementary web server by following these steps:
Firstly, ensure that you have Node.js installed on your system. If not, you can download it from the official Node.js website and follow the installation instructions.
Once done, open up a text editor of your choice and follow these steps:
1. Import the http module:
```
const http = require(‘http’);
```
1. Create a server:
```
const server = http.createServer((req, res) => {
// Your server code here
});
```
1. Write a response for the server to send when a user accesses your page:
```
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hello World\n’);
});
```
1. Now that you have a server, you need it to listen on a specific port for any incoming connections:
```
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
```
Your complete Server code will look like this:
```
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}/`);
});
```
You can save this file as ‘server.js’ (or any name of your choice, but make sure to retain the .js extension) in any directory.
Running your server:
Open up a command prompt/terminal window and navigate to the directory where your server file is located. For instance, if you saved your file on the desktop, you might have to type ‘cd Desktop’. Once you’re in the correct directory, you simply have to start your server using Node:
```
$ node server.js
```
You will now see a console message stating “Server running at http://127.0.0.1:3000/”. If you open up any web browser and go to http://127.0.0.1:3000/, you should see a plain webpage displaying ‘Hello World’.