javascript - Node Module Caching -
i creating application using express , ran issue using module.exports. have route handle checking out user creating pdf based on order. keep things modular have been separating route functionality modules , requiring them when necessary, example:
route1.js
module.exports = function(req, res){ // route functionality };
routes/index.js
route1 = require('./route1'); router.post('/api/v1/route1', route1);
this has been working great keep things organized, created route lot of complex functionality , there seems issue caching. first time call route works fine, second time call it gets stuck in infinite loop because 1 of variables last request persisting , never breaks out of loop because greater number needs equal loop exit. resetting of variables @ beginning of function passed through module.exports.
to fix problem no longer exporting route functionality , instead passing directly route. here example:
works everytime
router.post('/api/v1/dostuff', function(req, res){ var count = 0; var dosomething = function(){ // if count === else break // else add 1 count , run function again } });
works first time
do_something.js
module.exports = function(req, res){ var count = 0; var dosomething = function(){ // if count === else break out , else // else add 1 count , run function again // works first time second time // count persisting , greater // number checking against // never breaks out of function } };
routes/index.js
var dosomething = require('./do_something.js'); // works expected first time call made router.post('api/v1/dosomething', dosomething);
so why when using module.exports function work expected once? thinking has node module caching.
i'm quite not sure module caching have function in app work quite similar yours. try export module
something.controller.js
exports.dosomething = function(req, res){ // code }
and index.js
var controller = require('./something.controller.js'); router.post('/api/v1/dosomething', controller.dosomething);
hope help
Comments
Post a Comment