07_05_GuyT
07_05_GuyT

Reputation: 2887

save object in module and access it from different modules

I am using the following code to parse json data and keep it internally in my module, for example when the server is (like npm server.js) I'm using the function parse which parses the json files.
At the end these parsed jsons are kept in the object configObj and I want that during user request's(via express) to get this object in the router module or other modules.

How do I achieve this?

var configObj;
parse = function () {
        return fs.readFileAsync(file, 'utf8')
            .then(function (res) {
                return JSON.parse(res)
            }).then(function (jsonObj) {
                configObj = jsonObj;
                return jsonObj;
            })
....
        })
    };
    module.exports = {
        parse: parse,
        configObj: configObj
    }

The parse function is called only once and I want to access to the configObj many times in different modules.

Upvotes: 13

Views: 1030

Answers (2)

stdob--
stdob--

Reputation: 29172

If you use express best way is app.set: when you require your parse module function save result for example by:

app.set("parse.configObj",configObj)

and get it when need:

app.get("parse.configObj")

Or you can use require.cache scope after require:

server.js:

var parse = function () {
        return fs.readFileAsync(file, 'utf8')
            .then(function (res) {
                return JSON.parse(res)
            }).then(function (jsonObj) {
                if (typeof require.cache.persist === "undefined") {
                  require.cache.persist = {};
                }
                require.cache.persist.configObj = jsonObj;
                return jsonObj;
            })
    })
};
module.exports = { parse: parse }

app.s

var parse = require('./server.js').parse();

routes/index.js

console.log( require.cache.persist.configObj );

Upvotes: 3

michelem
michelem

Reputation: 14590

You could use something like node-persist:

var storage = require('node-persist');
storage.setItem('config', configObj);
console.log(storage.getItem('config'));

Upvotes: 6

Related Questions