Introduction to Node.js

Overview | Modules | Client&Server | Setting up Server

Introduction to Node.js

Hi there,
In this article, we'll cover the following topics.

  • Overview of node.js
  • Basic modules
  • Client and server
  • Setting up a server using node.js

Overview of node.js

Javascript Initially, was confined to the browser and we used it to add interactivity to the web page and we couldn't run javascript on the server, but "NODE" allowed us to do so.
Before we proceed let's understand how the computer understands code.

Computers understand machine code. Since machine code was difficult to read and write we came up with assembly language, furthermore, to make code more comprehensible we came up with c++, which when written in the system is compiled to assembly language and proceeded by converting it to machine code.

Now Javascript is a language that is abstracted even more from c++ to make programming easier. This means our computer system does not understand the javascript if run on the system. How is this possible?

Our browser has what is known as a javascript engine, which converts javascript code to machine code in run time. Because of this engine javascript cannot run outside of the browser as there is no way for our system to understand it outside the browser. You can assume this engine to be a listener for javascript code on only the browser.

Down the lane, one smart guy called Ryan Dahl moved this javascript engine on the server environment that enabled us to write javascript code on the server. Since this engine is written in c++ by default it can directly run on our system.

You can think of node.js as a wrapper that wraps this javascript engine on the server

What is node.js

Node.js is used to build back-end services. The reason for its popularity is that node.js is asynchronous, i.e it does not wait for the incoming request to complete before taking the next request. Node.js eliminates the waiting time and simply continues with the next request.

  • Node.js is an open-source server environment that means you can check out its source code and even contribute to it.
  • NodeJs is cross-platform i.e Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • and as mentioned above Node.js uses JavaScript on the server.

What can node.js do

  • Node.js handles javascript on the server-side. since we can use javascript, Node.js can generate dynamic web content.

  • Node acts as a middle man between the frontend application and the database, i.e Node.js can collect data from the frontend ('eg: forms') and either update/add or delete it from the database, i.e formulates an appropriate response based on the request.

  • Node.js can also modify/add/delete files within its own server

Benefits of using node.js

  • If you're familiar with javascript, there is no need to learn an extra language for the server.
  • can share code between frontend and backend as both use the same code. i.e Javascript.
  • very popular and has a huge community behind it. Therefore it's easier to find 3rd party packages, hence you don't need to reinvent the wheel.
  • Uses an event-driven, non-blocking I/O model that makes it lightweight & efficient. Now, what is event-driven? it is a computer programming paradigm in which control flow of the program is determined by the occurrence of events. These events are monitored by code known as an event listener that, if it detects that its assigned event has occurred, runs an event “handler”, typically a callback function or method. This handler deals with the event by responding to it with program code.

Basic modules

A module is a single or a collection of reusable javascript files which is used by node.js application.

There are 3 types of modules

  • Core modules
  • Local Modules
  • Third-party modules

Core modules

Core modules are lightweight as they include bare minimum functionalities. these are compiled and loaded automatically when the node.js process begins. However, you need to import the core modules first in order to use them in your application.

The following table lists some of the important core modules in the node.js application

  • 'http': which holds methods that work around http requests/response.
  • 'os': provides operating system-related utility methods and properties.
  • 'path': Provides methods to handle file paths
  • 'querystring: To handle URL query string
  • 'fs': provides methods to interact with the file structure.
  • 'url': URL module includes methods for URL resolution and parsing.
  • 'util': util module includes utility functions useful for programmers.

Loading code modules.

although these core modules are compiled and loaded, you still need to load the required module for the application.

var moduleVariable=require('module_name');

Local modules.

Local modules are modules created locally in your node.js application. these modules include separate functionalities of your application in separate files and folders. you can also package and distribute via npm. for example, you can create a local module to check the schema of values entered via form or a separate module only to handle routes.

In node.js modules should be placed in separate javascript files and always remember to export these modules so that they can be used in other files.

file name log.js

log={
info:()=>{console.log('This is Info')},
warning:()=>{console.log('This is warning')},
error:()=>{console.log('This is error')}
}

module.exports=log

to use log in another file check out the below code

logVal=require('./log.js');

//this is how we access the values within log
console.log(logVal.info);
console.log(logVal.error);
console.log(logVal.warning);

Let's talk a little bit about the module.export object. module.export is a special object which is included in every Javascript file in the node.js application by default.

"module" is a variable that represents the current module. while export is an object that will be exported as a module. thus in the above case module.export takes in the object log and exports it.

Third-party modules.

A node package manager is a command-line tool that installs, updates, or uninstalls node.js packages in your application. the online node community creates a multitude of packages that you can use without the need to code from scratch.
npm is included during node.js installation.

  • npm -v: To check if the node.js has installed npm correctly go to the terminal and type npm -v. you'll get the version you are operating on.
  • npm install module_name: this installs the module in the current directory. This module is a third-party library.
  • npm install -g module_name: This installs the module globally, so it's accessible to all node.js applications.

Client and server

The objective of learning node.js is to ultimately create a server powered by node.js, A server is a system that listens to incoming request and responses appropriately.

How does this whole process work? Basically, we type in a URL in the browser that sends a request to the server and the server sends back a response appropriately. Now your probably wondering how does the browser know which server to send it to, as there are million of servers available. The answer to that is IP addresses.

Once a system is connected to the internet it gets a IP address. To get the resources of the server you need to know its IP. Since IP can be hard to remember we came up with a abstraction of the IP address known as domain name,eg "google.com". once you write this abstraction the dns converts it to IP and traverses it on the network to find the appropriate server.

This communication via the browser and the server is via HTTP, which is basically a set of instructions on how the communication occurs over the network.

Side-note:
localhost is like a domain name on the web that points to your own system, which acts as a server to your website.

port numbers are like doors on your system. you may have different applications, all connected to the internet and transversing data at the same time. to prevent cross transfer we use different ports for different applications

console.log when executed in node.js runs on the server and not the browser

Setting up a server using node.js

There's this unwritten rule in programming, that you cannot proceed to learn without knowing how to display hello world.

  • Create a file with a .js extension

  • Type the following in the .js file

var http = require('http');

server=http.createServer(handleRequest);
server.listen(8080,()=>{console.log('listining on port no: 8080'});

function handleRequest(req, res) {
 res.writeHead(200, {'Content-Type': 'text/html'});

 res.end('Hello World!');
}
  • Open the terminal and move to the directory where the .js file is located

  • Type the following in the terminal
    node filename.js

Output

Now, your computer works as a server!
open your internet browser, and type in the address:> localhost:8080
If anyone tries to access your computer on port 8080, they will get a "Hello World!" message in return!

output.png

Now let's explain the code

the above code may look complicated but trust me it's not!

 var http = require('http');


To understand the above line of code let's understand what are modules. Modules are basically similar to .js libraries, i.e a set of functionality you want to include in your application. node.js has a couple of built-in modules, a few of them are listed below

  • 'http': which holds methods that work around http requests / response.
  • 'os': provides operating system-related utility methods and properties.
  • 'path': Provides methods to handle file paths
  • 'querystring': To handle url query string

To include a module, we use the require() function with the name of the module as an argument
eg:

var http = require('http')

here the argument http is an object which holds a list of methods that can work on HTTP request and response.

server=http.createServer(handleRequest);

In the above line of code, we use an HTTP method to create a server and pass a function in it. This function tells us how to deal with requests and responses.

server.listen(8080);

.listen() is an HTTP method that takes in 2 arguments, the first argument tells us which port number has to be used to communicate with the previously created server, the second one is a callback function that logs a message on the node[optional]

function handleRequest(req, res) {
 res.writeHead(200, {'Content-Type': 'text/html'});

 res.end('Hello World!');
}

The above is a function that is called when a request is made to the server, that uses port 8080 to communicate.

the above function takes in 2 parameters:
request
response
the request has a set of methods that help us work with the URL that is sent to the server. while response deals with what is sent to the client.

response.writeHead(statusCode[, statusMessage][, headers]);

response.writeHead takes in 3 parameteres

  • statusCode takes in 3 numbers that tell the user whats the status of the request, the most common one you would have noticed is 404.

  • [status_message] is optional, It accepts any string that shows the status message.

  • [headers] is optional, here we mention the type of data that we send back to the client. In the above example, we wrote 'text/html' which means that the data that we send may or may not have Html code in it.


res.end('Hello World!');

The above line of code tells the browser that this is the end of the response the parameter is optional. Through this parameter, you may send the data.