Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store session data in file in expressjs?

When user login, i am storing data in session like this :

   req.session.user = userData;

And it is working fine but when i restart in nodejs, the session is null. Then user need to login again.

I want to create a file based storage for session.But after a lot of search, i got the way to store data in database but i dont want to store session data in database. I want to store data in file.

Is there a nodejs module to store the session data in file?

like image 858
rajeshpanwar Avatar asked Apr 02 '14 13:04

rajeshpanwar


1 Answers

You can use session-file-store. can refer below working example.

var express = require('express');
var app = express();
var session = require('express-session');
var FileStore = require('session-file-store')(session);

app.use(session({ secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
    store: new FileStore,
    cookie: { maxAge: 3600000,secure: false, httpOnly: true }
  })
);

app.get('/', function (req, res) {
  if (req.session.views) {
    req.session.views++;
    res.setHeader('Content-Type', 'text/html');
    res.write('<p>views: ' + req.session.views + '</p>');
    res.end();
  } else {
    req.session.views = 1;
    res.end('Welcome to the file session demo. Refresh page!');
  }
});

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});
like image 169
Kishan Rajdev Avatar answered Sep 20 '22 01:09

Kishan Rajdev