Search code examples
node.jssessionexpressmkdirfs

Issue with Express sessions and fs module


app.post('/register', express.BodyParser(), function (req, res){

   var newu = new UserModel({});

   newu.user = req.body.nuser;
   newu.pass = req.body.npass;
   newu.mail = req.body.nmail;

   var pathu = __dirname + '/users/' + req.body.nuser;

   newu.save(function (err, newu){

       req.session.user = new.user;

       if(err) throw err;

       fs.mkdir(pathu, function (err){

           if (err) throw err;

        });    

   });

   res.redirect('/home);

});

Always when the fs.mkdir is executed, I lose all the current Express' sessions, is there any way to execute fs.mkdir and keep all the Express' sessions?


Solution

  • Not sure how it's causing your symptoms, but this line:

    req.session.user = new.user;
    

    should likely be:

    req.session.user = newu.user;
    

    UPDATE

    The root of the problem is that creating the directory is triggering nodemon to restart the app and the default in-memory session store loses all sessions when that occurs. The fix is to use a persistent session store like Redis via connect-redis.