Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 628
07_05_GuyT Avatar asked Aug 03 '15 10:08

07_05_GuyT


People also ask

Can modules use other modules?

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names, if placed at the top level of a module (outside any functions or classes), are added to the module's global namespace.

How do you access classes outside modules in typescript?

In typescript by using an import statement, a module can be utilized in another module. any variables, classes, methods, or other objects declared in a module are not accessible outside of it. The keyword “export” may be used to construct a module, and the term “import” can be used to import it into another module.

Can you export with module exports?

When you export a module, you can import it into other parts of your applications and consume it. Node. js supports CommonJS Modules and ECMAScript Modules.


1 Answers

You could use something like node-persist:

var storage = require('node-persist');
storage.setItem('config', configObj);
console.log(storage.getItem('config'));
like image 189
michelem Avatar answered Nov 10 '22 12:11

michelem