MrMangado
MrMangado

Reputation: 993

Deal and keep node.js/express sessions

I'm currently working on a web app, this web app every time fs.mkdir is called, delete all the current express sessions, so I need a way to keep all this sessions. I was trying to keep all this sessions with connect-mongodb and connect-redis, but neither works, nodemon always says that req.session is undefined. I don't know what I have to do to keep all the session.

I need a way to keep all the sessions, don't lose them when fs.mkdir is executed, and a tutorial for it, because I don't found any good and complete tutorial for this yet, anyone works! I was reading all releated with this here, in Stackoverflow, but anything works! Please help!

Upvotes: 2

Views: 739

Answers (1)

balazs
balazs

Reputation: 5788

it sounds very exotic, that after fs.mkdir your session erased. (I found your other SO question)

But back to the question, here's a little code snippet how you can use sessions (redis).

var express = require('express')
  , fs = require('fs')
  , http = require('http')
  , RedisStore = require('connect-redis')(express)
  , sessionStore = new RedisStore()
  , app = express()
  ;

app.configure(function(){
  app.set('port', 3000);
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('secret'));
  app.use(express.session({
    store: sessionStore
  }));
  app.use(express.static(__dirname + '/public'));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.get( '/', function(req, res){
  res.setHeader("Content-Type", "text/html");
  console.log( req.session );
  console.log( '------------------------' );
  res.end( 'root' );
});

app.get( '/dir/:id', function(req, res){
  console.log( req.session );
  console.log( '------------------------' );

  fs.mkdir( req.params.id );
  if ( req.session.dirs === undefined )
    req.session.dirs = [];
  req.session.dirs.push( req.params.id );

  console.log( req.session );
  console.log( '------------------------' );

  res.setHeader("Content-Type", "text/html");
  res.end( 'dir' );
});


server = http.createServer(app).listen(3000);

you should read the docs of express, and browse the examples of express

Upvotes: 1

Related Questions