It is easy to run your own server nowadays. Nodejs, makes it look like a piece of cake.

Once you have installed Node, let’s try building our first web server.

Create web directory:

Let’s start by creating our server directory.

1
$ mkdir nodejs-server

Server js file

Once we changed to the nodejs-server directory,

1
$ cd nodejs-server

create a server.js with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const http = require('http');

const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.write(
`
<h1> Hello! Welcome to AshKeys! </h1>
`
);
});

server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

Now our server is ready to be created.

Run as node

This is it! All we have to do now is to run as a node file.

1
2
$ node ./server.js
Server running at http://localhost:3000/

Now our server is listening to port 3000 and welcomes you to AshKeys

Tip: When it comes to routing it is express that comes at best!