javascript - Export function first and object subsequently -


i have custom module , provide method initialize on first require, directly return object on subsequent requires.

but module gets cached when first required , therefore subsequent requires still return init function instead of returning obj directly.

server.js:

var module = require('./module.js'); var obj = module.init(); console.log('--debug: server.js:', obj); // <-- works: returns `obj`.  require('./other.js'); 

other.js:

var obj = require('./module.js'); console.log('--debug: other.js:', obj); // <-- problem: still returns `init` function. 

module.js:

var obj = null;  var init = function() {     obj = { 'foo': 'bar' };     return obj; };  module.exports = (obj) ? obj : { init: init }; 

how can work around problem? or there established pattern achieving such?

but keep obj cached, because real init work rather not on every require.

there ways clear require cache. may check here node.js require() cache - possible invalidate? however, think not idea. i'll suggest pass module need. i.e. initialize once , distribute other modules.

server.js:

var module = require('./module.js'); var obj = module.init();  require('./other.js')(obj); 

other.js:

module.exports = function(obj) {     console.log('--debug: other.js:', obj); // <-- same obj } 

module.js:

var obj = null;  var init = function() {     obj = { 'foo': 'bar' };     return obj; };  module.exports = { init: init }; 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -