Node.Js: How to use Session in NodeJs to store information

As an asynchronous event driven framework, Node.js is designed to build scalable network applications.

Node is similar in design to and influenced by systems like Ruby’s Event Machine or Python’s Twisted. Node takes the event model a bit further, it presents the event loop as a language construct instead of as a library. In other systems there is always a blocking call to start the event-loop. Typically one defines behavior through callbacks at the beginning of a script and at the end starts a server through a blocking call like EventMachine::run(). In Node there is no such start-the-event-loop call. Node simply enters the event loop after executing the input script. Node exits the event loop when there are no more callbacks to perform. This behavior is like browser JavaScript -— the event loop is hidden from the user.

HTTP is a first class citizen in Node, designed with streaming and low latency in mind. This makes Node well suited for the foundation of web library or framework.

According to a survey, it is cleared that PHP is 70% slower tha NodeJs.

Steps to create Session.

1)  First of all, install Client Sessions in your node application. For this, you can go to your directory by using Command Prompt and there copy these lines. npm install client-sessions

2)  Now you have to add this line in your app.js file. var session = require(‘client-sessions’);

3)  Now add below lines in your app.js file at just below to your app variable. It means paste below lines where you have written var app=express();

cookieName: ‘session’,
secret: ‘jgsdggsdfkbkjbhdjameerkhanjimcute’,
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,

4)  Now got to your index.js file which can be found in routes folder and initialize your session variable where you want to store value in session. Such as

var collection=db.get(‘registercollection’);

5)  Now modify your router page on which you want to show the session value. Such as

router.get(‘/’, function(req, res, next) {
if(req.session && req.session.user){
res.render(‘index’, { title: ‘Express’ ,username:req.session.user.username});      }

6)  And now you can access your session on your jade page by writing this line.

h1 Hello, #{username}

Enjoy coding…………..


One thought on “Node.Js: How to use Session in NodeJs to store information

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s