RedGiant
RedGiant

Reputation: 4748

how to return a value from express middleware as a separate module

I have put the server setting script into a separate js file called server.js. My problem is that I don't know how to get the value of cookie_key from the express middleware function and pass it back to the index.js file.

server.js:

var express = require('express'), 
app = express(), 
http = require('http').createServer(app),
cookie = cookieParser = require('cookie-parser'),
url = require('url');

module.exports = {

 use_app : function(){
  app.use(function (req, res, next) {
  var cacheTime = 86400000*7; // 7 days
  if (!res.getHeader('Cache-Control')) 
   res.setHeader('Cache-Control', 'public, max-age=' + (cacheTime / 1000));
   next();
  }); 
 },

 get_app : function(callback){
  app.use(cookieParser());
  app.get('/id/:tagId', function(req, res){ // parse the url parameter to get the file name
   function getkey(err,data){ // get users' session cookie
    var cookie_key;
    if(err)
    {
      callback(err);
    }
    cookie_key = req.cookies["session"];
    callback(cookie_key);
   }
   var filename = req.param("tagId");
   res.sendFile(filename+'.html');
  });
 }

}

index.js:

var server = require('./server'),
server.use_app();
server.get_app(); // how to get the cookie_key when calling this function?
console.log(show_cookie_key_from the module); 
if(cookie_key !== undefined)
{
   // do something
}

I tried to write a callback function to fetch the cookie key but I don't think it's working.

Upvotes: 0

Views: 69

Answers (2)

Timothy Strimple
Timothy Strimple

Reputation: 23070

Update from A.B's answer:

var server = require('./server');
server.use_app();
server.get_app(function(cookie){
  if(cookie !== undefined)
  {
    // do something
  }
}); 

But I still think there is something strange about this setup, what exactly are you trying to accomplish with splitting the app up like this?

Upvotes: 1

A.B
A.B

Reputation: 20445

Since you are using callback function and that is being poplulated with cookie value , you can get this like following:

var server = require('./server');
server.use_app();
 server.get_app(function(cookie){
cookie_key= cookie
if(cookie_key !== undefined)
{
   // do something
}
}); 

Upvotes: 0

Related Questions