javascript - How to share the scope within module.exports -
inside handler.js , have exported 2 functions. 1 initialize()
, other handle()
. initialize function use load handler dynamic based on application settings. , have shared variable var handler
outside module.exports function.
handler = new handler(app);
new instance created assign shared variable var handler
. , inside handle()
function shared variable var handler
. used
dynamically require()
file in web request time not idea. initialize()
method created , called in application start time.
let me know suggestion remove shared variable 'handler'
var handler; module.exports = { initialize : function (app){ var handler = require(path.resolve(app.basedir, app.settings.handler)); handler = new handler(app); }, handle : function handle(ctx) { var urltohandle = ctx.url; return handler.resolveurl(ctx) .then(function (json) { ctx.layoutjson = json; return ctx; }) .catch(function (e) { throw e; }); } };
not sure if got right, if call initialize once can that:
var app = require('path-to-a-file-which-return-app'); var handler = require(path.resolve(app.basedir, app.settings.handler)); var handler = new handler(app); module.exports = { handle : function handle(ctx) { var urltohandle = ctx.url; return handler.resolveurl(ctx) .then(function (json) { ctx.layoutjson = json; return ctx; }) .catch(function (e) { throw e; }); } };
now require called once, since node cache you.
Comments
Post a Comment