Friday, August 3, 2018

Understand nodejs Basics - webserver tutorial

Understanding Nodejs 

Nodejs is an opensource framework for building Server-side applications based on javascript. It is javascript runtime based on Chrome V8 Javascript engine. Basically, You can write your own web server using this environment. Nodejs is growing popular day by day because of its features, simplicity, and architecture. Nodejs can be run on any operating System like Windows, MacOS, and Linux/Unix/Ubuntu. It is platform Independent.

Nodejs Advantages or pros

  • Provides Non-Blocking and Event-Drive programming features to handle the concurrent request
  • It is based on javascript
  • Scalable and network applications can build with simple code
  • Simple to learn
  • It is a single threaded model
  • Performance is very good as it uses javascript in the server side

Disadvantages or cons

  • Learning Curve
  • Not suitable for Multithreaded Model
  • Not enough tools 

Basic Web server Example

the web server is a server which clients send the request to the server, in turns server returns response. Here request and response are based on HTTP protocol
To start the basic web server, First, you need nodejs environment installed. Which provides node and npm commands. There are many ways we can create/usage web server. I am discussing custom code and using another npm library

Nodejs Http Module example

This is writing our own server using inbuilt modules.
It is very easy to write a web server using HTTP module
 const http = require('http')
const defaultPort = 3000

const handler = (request, response) => {
  response.end('Basic Web server Server')

const webserver = http.createServer(handler)

webserver.listen(defaultPort, (error) => {
  if (error) {
    return console.log('Error ocurred during starting a server', error)

   console.log('Web server is up and running at 3000 ................')


You need to use HTTP module and import using the required function

Using http-server npm package manager

http-server library provides web server capabilities. First, you need to install it using this below command npm install http-server -gthis installs http-server package globally which can be accessed from anywhere. we are accessing from the command line

http-server path options here the path defaults to a public folder, if the public is not available, / considered
There are various options you can configure it

web server configurations

-p for the port which server listens on
-s HTTPS enabling
-o Once the server is up and running, automatically opens a browser window.
This is about the basics of nodejs environment.

Related article