Vlad Vinnikov Vlad Vinnikov - 4 months ago 13
Node.js Question

How to pass variable from app.js to routes/index.js?

I'm using shrinkroute https://npmjs.org/package/shrinkroute to make links in nodejs. I get error 500 ReferenceError: shrinkr is not defined

How to pass shrinkroute to routes/index.js? Is there a better way to create url by passing query string args?

//app.js
var app = express();

var shrinkr = shrinkroute( app, {
"user": {
path: "/user/:id?",
get: routes.showOrListUsers
}
});
//url method works in app.js
var url = shrinkr.url( "user", { id: 5, page:40, type:'a' } );
console.log(url);

app.use( shrinkr.middleware );

//routes/index.js
exports.showOrListUsers = function(req, res, next) {
console.log(req.params);
//shrinkr errors out in index.js
var url2 = shrinkr.url( "users", {name: "foo"});
console.log(url2);
}

Answer

One solution would be to store shrinkr in your app object using app.set:

// app.js
...
app.set('shrinkr', shrinkr);
...

In routes/index.js, you can access it through the req.app or res.app objects:

exports.showOrListUsers = function(req, res, next) {
  var shrinkr = req.app.get('shrinkr');
  ...
};