NodeJS : Continuation Local Storage or Thread Local Storage?

Sometimes you need piece of data, most of the time request/response objects, between different events of a request where it is generally not accessible. Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. 

Problem

Suppose you have a rest API (/users) that serves the user data. The handler of this API calls the service layer to get user data. The service layer calls your facade layer to get data from either directly from the database or from third party URL. After getting the data from different sources, facade layer combines the data and return to service layer that further returned to the actual API.

Now API layer accepts the cookie that contains some token to validate the request. The same token is required at facade layer. One way is to pass the token extracted from cookie at API layer to service layer that further will pass to facade layer.

In some cases, there can be other layers and events in which you need the same token or user data. Passing data, layers to layers is not a good practice and not a cleaner way.

So to sort the same problem Continuation Local Storage (CLS) comes into the picture.

What is Continuation Local Storage (CLS)?

Continuation Local Storage is a package to access the current express request/response object from a point where that is not readily accessible. It works like thread-local-storage in multithreading programming like java. As nodejs is single threaded it supports events/callbacks instead of multi-threads. And to achieve the same It uses the concept of **namespace**.

Node.js is asynchronous and uses an event loop to manage the asynchronicity, AsyncListener allows you to write software that can keep hold of information across callbacks.

What is Thread Local Storage (TLS)?

From Wikipedia

Thread Local storage (TLS) is a computer programming method that uses static or global memory local to a thread.

Setup

Let’s get started with Continuation Local Storage

1) Install the continuation-local-storage package

npm install continuation-local-storage --save

2) Create namespace that will hold the objects that we want to access at global level

let app = express();
let cls = require('continuation-local-storage');
let namespace = cls.createNamespace('com.domain');

3) Define middleware that will bind the request and response object to namespace

app.use((req, res, next) => {
   var nameSpace = cls.getNamespace('com.domain');
   // wrap the events from request and response
   nameSpace.bindEmitter(req);
   nameSpace.bindEmitter(res);
 
   // run middleware in the scope of the namespace that we have created
   nameSpace.run(() => {
       // set data to the namespace that we want to access in different events/callbacks
       namespace.set('data', "any_data");
       next();
   });
});

4) Now this data can be accessed at any layer. For demo, logging the data that was set in the namespace

//logger.ts

var getNamespace = require("continuation-local-storage").getNamespace;
let nameSpace = getNamespace("com.domain");
let data = nameSpace.get("any_data");
console.log("data : ", data);
Nodejs Interview Questions

Important Interview Questions for Node.js

1) What is Nodejs ?

2) What is NPM ?

3) Different types of API’s exist in Node (api methods)?

4) What is event looping ?

5) What is event emmiter in node.js ?

6) What is asynchronous calls in Node.js ?

7) Suppose we have 5 apis, we have to hit fifth api when all four have been completed.How can we do it ?

8) What are promises ?

9) What is promise all in node.js ?

10) What is clustering in node js?

11) Core features in node.js ?

12) Can I send body params in GET request ? if yes then how ?

13)  What are middle-wares in node.js ?

14) What is the use of next in node.js ?

15) Different types of exit polls in node.js ?

16) Explain Process in node.js ? 

17) Why node is single threaded ?

18) New features in node.js ?

19) What are create, read streams ?

20) Inheritance in node.js ?

21) How can I secure my cookies in node.js ?

22) What is the passport in node.js ?

23) Best way to manage the session in node.js ?

24) What do you mean by child processes in node.js ?

25) What is the cross-domain problem ?

26) If I want to solve the cross-domain problem for only specific type of APIs , how can I do it ?

27) How can we integrate Third party APIs in node.js ?

28) Explain callback in node.js ?

29) What is callback-hell in node.js? how can I solve this?

30) How can we install local and global dependencies in node.js ?

31) What are streams in node.js ?  

32) Explain package.json file in node.js ?

33) What is the meaning of tilde and caret in package.json

34) How can we control versioning about packages in node.js ?

35) Difference between dependencies and dev dependencies ?

36) What is npm start ?

37) If I want to explain my own command with npm how can I do it ?

38) Explain logging in node.js ?

39) Name node.js framworks ?

40) What is express

41) How can we add the prefix in node.js apis?

42) Use of cookie-parser in node.js?

43) How to make APIs session less ?

Further Reading

Javascript Interview Questions

AngularJS Interview Questions

NPM : Node Package Manager

NPM is a node package manager for the JavaScript programming language.It is the world’s largest software registry. It consistes of a command line client also called NPM and also the default package manager for the javascript runtime environment Node.js. It also have online database of public packages called the NPM registry that hosts thousands of free packages to download and use. Moreover it consists of a command line client that interacts with a remote registry (packages in the registry are in CommonJS format and include a metadata file in JSON format).

Functionalities of NPM (Node Package Manager)

1) Command line utility to install Node.js packages
2) Provide dependency management and version management of Node.js packaged
3) provide online repositories for Node.js packages

Reference:

https://docs.npmjs.com/getting-started/what-is-npm

The NPM program is installed on your computer when you install Node.js. To install node.js refer: 

http://array151.com/blog/nodejs-tutorial-and-set-up/

we can check it is installed or not by

$ which npm
$ npm --version
4.2.0

With Node Package Manager we can install packages in local and global mode. To install packages in local mode we need following command

npm install packagename

In local mode it installs the packages in node_modules folder in parent working directory.This location is owned by the current user.

To install packages in global mode

sudo npm install forever -g

This means you would have to use sudo to install packages globally, which could cause permission errors when resolving third-party dependencies, as well as being a security concern. Global packages are installed in {prefix}/lib/node_modules/ which is owned by root (where {prefix} is usually /usr/ or /usr/local)

To check the npm configuration we need

$ npm config list
; cli configs
user-agent = "npm/3.10.10 node/v6.10.3 linux x64"
; userconfig /home/sitepoint/.npmrc
prefix = "/home/sitepoint/.node_modules_global"
; node bin location = /usr/bin/nodejs
; cwd = /home/sitepoint
; HOME = /home/sitepoint
; "npm config ls -l" to show all defaults

This gives us information about our install. we can also get our current global location by

$ npm config get prefix
/usr/local

This is the prefix, we can also change the value of prefix also by using this command 
For this let first create a new folder in our home directory to save it

$ cd ~ && mkdir .global_node_modules
$ npm config set prefix=$HOME/.global_node_modules

To uninstall the packages we can use

npm uninstall packagename

To fetch the list of installed packages we can use

npm list

There are lot of commands for more info refer:

https://docs.npmjs.com/cli/access

 

 

Node.js tutorial with basic Setup and Installation

What is Node.js 

Node.js is an open source cross-platform for developing server-side and networking applications. It provides runtime environment and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Moreover applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, Linux moreover its package ecosystem, npm is the largest ecosystem of open source libraries in the world.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Historically, JavaScript was used primarily for client-side scripting, in which scripts written in JavaScript are embedded in a web page’s HTML to be run client-side by a JavaScript engine in the user’s web browser. It enables JavaScript to be used for server-side scripting and runs scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser.

 

Previously javascript code is in working on the client side(front end) only. But with the power of node.js, we can now play with it on the server side (backend) also to generate the dynamic content. Node.js is actually based on the event loop programming model. It repeatedly waits for events and then runs any event handlers subscribed to those events and the event loop runs in a single thread.

Events can be:

1) A new HTTP request coming our way
2) Timer wait is complete
3) Next chunk of data is ready to be written to the file

Due to this process, multiple requests are handled concurrently by a single Node.js process. As long as these event handlers are small and wait for yet more events themselves everything works out nicely and no Javascript code is ever executed in parallel, all of this runs in a single thread.

Why node is single threaded?

Node.Js was built with the intention of supporting asynchronous operations and the fact is that the asynchronous operations have better performance and scalability when they are single-threaded over multi-threaded. This is the reason the Node.Js is single threaded.

Features of Node.js

1) Server Side java Script
2) Versatile
3) High Reliability
4) Asynchronous
5) Single Threaded
6) Run Anywhere
7) No Buffering
8) Easy Integration with JS Stacks
9) Speedy Execution

Top websites powered by Node.js

1) https://www.paypal.com
2) https://www.groupon.com
3) https://www.wsj.com
4) https://www.shutterstock.com
5) https://www.opencare.com

For more info visit: https://codebrahma.com/top-10-sites-powered-by-node-js/ 

Installation

For Linux follow the guide.

For Windows download the installer.

To check if nodejs is installed successfully, Open command prompt and type

node -v

What is NPM 

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client also called npm, and an online database of public packages called the npm registry.

Reference:

https://docs.npmjs.com/getting-started/what-is-npm

Set up node.js application

Before create a node.js application we need to install express framework using npm command. ( Express is a lightweight and easy to use Node.js framework that helps to create and manage our apllication into MVC architecture.Express provides a robust set of features to develop mobile and web applications)

Reference:

https://expressjs.com/

To install express run 

npm install express -g

The above command will install express globally on your machine. then type

npm install express-generator -g

It will install the express generator globally on your machine. After that to create the skeleton of node app just type 

express projectName

This will create the node.js skelton with name projectName, where project name is the name of your app skeleton. After that just go in the app structure and install the app dependencies by 

cd projectName
npm install

It will create the node modules folder where it install all the dependencies, after that just type npm start command to start the server and check it works or not. To check its proper working after run the start command just open any browser and type localhost:3000 to check the server is listening or not (3000 is the default port uses by it).

npm start

Now open any browser and hit localhost:3000

en_USEnglish
en_USEnglish