node js

Learn Node.js -Intro

Node.js, an open-source and cross-platform server environment that allows us to run JavaScript on the server.

node js

Key features of Node.js:

  • Event Driven architecture
  • Non blocking Input/Output API
  • Real time two way communication between client and server
  • built on Google Chrome’s JavaScript V8 Engine
  • Very Fast 
  • Never buffer any data and simply output the data in chunks.

Best Use case scenarios for Node.js:

Node.js is recommended for streaming applications, like video audio websites, and event based applications. It is efficient for applications that needs high level of concurrency and less CPU usage. It is also recommended for Data Intensive Real-time Applications , single page applications ,and I/O bound Applications

Examples include:

  • Gaming applications and servers
  • Chat Applications
  • Streaming servers
  • Document sharing applications

Avoid Node.js for applications:

Try to avoid using Node.js where there are long processing times or for CPU intensive applications. Since it has a single threaded structure and if the application is taking time in scenarios like doing some calculations or long running processes, it won’t be able to execute other requests.

Download Node.js

We can download Node.js from the official web site: https://nodejs.org .Select the installer based on your operating system and install node in to your system.

Once installed, just confirm if it is installed properly.

Open command prompt and type

c:\test>node -v

v10.16.2

You should see a version number of the node that you have installed.

Let’s start with a simple example

Create a javascript file (example1.js) and add below snippets into that.

console.log("Hello World!");
console.log("Welcome to Learn Jobisite");

Now go to the command prompt and run

c:\test>node example1.js

Hello World!

Welcome to Learn Jobisite

 

Start with first Node.js example:

Usecase: Print hello world and Learn Jobisite in the browser. It needs to be run on a server on a given port, say 8081

Create a new javascript file (example2.js) and add below lines there.

var http = require("http");

http.createServer(function (request, response) {
   response.writeHead(200, {'Content-Type': 'text/xml'});
   
   response.end('Hello World!\nWelcome to Learn Jobisite');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Let’s understand the code before running. Basically this example consists of three parts. Firstly, we have to load or import the required modules or dependencies. Secondly, we need to have a server. And thirdly, we need to have the get the request and response back to the server.

1)    For any server related application, we need an Http module.

var http = require(“http”);

2)     Then we are creating a server which is listening on port 8081. Here we have default/wildcard request path defined means anything on this URL http://localhost:8080/(*) will run this method.

In response, we are setting up the response Http code and text back to the server.

http.createServer(function (request, response) {

   response.writeHead(200, {‘Content-Type’: ‘text/plain’});

   }).listen(8081);

3)     Sending response back to the browser.

response.end(‘Hello World!\nWelcome to Learn Jobisite’);

4)    This line is just for debugging.

console.log(‘Server running at http://127.0.0.1:8081/’);

 

Playing with the example:

1)    If I change the response code from 200 to 400.

The response will still be generated to the browser with the statements but http code will be 400.

Request URL: http://localhost:8081/dsdsds
Request Method: GET
Status Code: 400 Bad Request
Remote Address: [::1]:8081
Referrer Policy: no-referrer-when-downgrade

 

2)    If I don’t put the content-type here

The application will still run and will use the default content-type here.

3)    If I don’t put the port number

The application will start but we will not able to execute the request/response as no port is listening.

4)    If I don’t import http

The application will throw below error:

http.createServer(function (request, response) {

^

ReferenceError: http is not defined

 

 

Frequently Asked Questions

 

What is the difference between setImmediate() vs setTimeout()?
setImmediate() -executes once event loop phase completes.
setTimeout() – executes if the wait reaches certain time in execution.


How can we enable tracing in Node.js?
Tracing helps to get V8, Node core and userspace code in a log file.
Use flag –trace-events-enabled to enable tracing.
This log file can be opened in chrome://tracing tab of Chrome.


What is a consistent style?
It is recommended to have a consistent style while working with big teams or independent developers.
Some tools like ESLint, Standard can help to achieve this and they offer static analysis also.

 

What are the exit codes in Node.js?
These codes are used to notify the end of a process.
Some examples:
Fatal Error
Non-function Internal Exception Handler
Internal Exception handler Run-Time Failure


What is the role of NPM in Node.js?
NPM (Node Package Manager) serves as n online repository for Node.js packages and provides a mechanism for installing and updating packages.


What is REPL in Node.js?
REPL (Read Eval Print Loop) helps to execute ad-hoc javascript statements and can be helpful for debugging and testing.


What is Node.js? Where can you use it?
Node.js is a server-side scripting language based on Google’s V8 JavaScript engine.
Mainly used to build scalable programs and web applications.
It is recommended to use Node.js in I/O intensive applications like streaming and chatting sites.


What are the Main features of Node.js?
It is asynchronous and event-driven I/O instead of separate processes/threads.
It can achieve using a single-threaded event loop and non-blocking I/O.

 

What is NODE_ENV?
Node.js recommends using NODE_ENV variable to flag the environment that’s been used.
For example, NODE-ENV, when set to production, can perform faster than usual.

 

What is the difference between fork and spawn?
In Node.js, spawn() launches a new process with the available set of commands without generating a new V8 instance.
fork() is a type of spawn() which also generates a new V8 engines instance. Here multiple workers can run on a single code base for multiple tasks.


How Node.js handle concurrency?
Node.js internally used various POSIX threads for various I/O operations such as File, DNS, Network calls, etc.
On any I/O request, Node.js creates these threads for execution and puts the event result into event stack which can be picked up by event loop.
This is how Node manages concurrency.

Leave a Comment

Your email address will not be published. Required fields are marked *