Client and Server in NodeJS

Client and Server in NodeJS

CommonJS backed module system in nodeJS

ยท

3 min read

Let's see how to create a server in nodejs from scratch.

TL;DR

NodeJS is mainly used to build server-side applications, which uses commonJS module systems and native javascript require method to build a server.

Me

Server

The word "server" has multiple related meanings depending on the context:

  1. Socket based architecture or an application that opened up a socket to listen for incoming requests
  2. HTTP request/response handling application
  3. The physical or virtual machine that is running that server application

Here, we're dealing the servers in context of "HTTP request/response handling application", let's call this server application in here.

HTTP(HyperText Transfer Protocol) is a protocol for communication between browser and server, So as a result browser and server only speaks in HTTP for communication.

Server Application

As explained above we are going to build that HTTP request/response handling application or a server application, using NodeJS. As of node server application it's build with javascript at its core so the convention server.js, and if it's php it would be server.php or so.

Node has built in modules for creating this server application using commonJS module system.

Let's build a server ๐Ÿš€

Folder Structure

nodeserver  /* root folder name */
|     
|__pages     /* views displayed to user/client */
|     |_index.html
|     | 
|     |_blogs.html
|     |
|     |_404.html
|
|__server.js    /* actual server application */
|

Defining the Modules and Paths

As of the context of node servers the module system are a area to focus.

For actually creating the connection on a specific port we use the http and for reading or parsing the pages/views we use fs built-in modules.

const http = require('http');
const fs = require('fs');

/* were the server actually runs its logic */
const server = http.createServer((request, response) => {
 /* paths are defined here.. */
});

/* opening the port to listen for requests*/
server.listen(3000, 'localhost', () => {
  console.log("Server running on port 3000");
})

Complete server code

server.js

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {

  // SET HEADERS for the response
  res.setHeader('Content-Type', 'text/html');
  let path = './pages/';   /*since all our views are in pages folder*/

/* We relatively get the path and read the apt file using fs module */
  switch (req.url) {
    case '/':
      path += 'index.html'
      res.statusCode = 200;
      break;
    case '/blogs':
      path += 'blog.html'
      res.statusCode = 200;
      break;
    default:  /* whatsoever undefinded are redirected to 404 page*/
      path += '404.html'
      res.statusCode = 404;
      break;
  }

/* if the path exists we read the data and send it as a response else error is displayed*/
  fs.readFile(path, (err, data) => {
    if (err) {
      console.log(err);
      res.end();
    }
    else {
      res.end(data);  /*end the response with the apt data*/
    }
  })

});

server.listen(3000, 'localhost', () => {
  console.log("Server running on port 3000");
})

Now open the command line run the server files, Here it;

node server.js

You should see the output as Server running on port 3000, So if you could go to the localhost:3000 you see the index.html displayed there.

Try some gibberish and checkout the server sending the 404.html page.

Yay you've successfully created a server application using NodeJS ๐Ÿ”ฅ


Major Takeaway

NodeJS is solely for building server-side application i.e HTTP request/response handling application as of the context of this post.

ย