简体   繁体   中英

How do I access a JSON object from one module to another using node.js?

This is my module1:

var fs = require('fs');
var obj;
    exports.module1= function(ret)
    {
    fs.readFile('source.json', 'utf8', function (err, data)
    {
        if (err) {
       return console.error(err);
        }
    obj=JSON.parse(data);
    console.log(obj);

    return obj;

});
}

Module2:

var module1 = require('./module1.js');
var obj=module1.module1();

var callback = function () {
console.log(obj);
};
setTimeout(callback, 10000);

The obj of module2 is not getting updated with returned value of module1. I am newbie btw.

You can share the object by passing it the the global context, which means the object will be usable from any file at any time, but the main JavaScript code (which requires the module) will be able to access it too. If you don't want it to access the code, comment this post and I'll make a script to do that.

The most simple way is to share the object :

global.__module_object = obj;

And anywhere you'll be able to access the object by doing global.__module_object.data = "Hello world !"; for example.

I believe ur problem is that fs.readFile is an async call and its return value will not be passed to the obj defined in Module2.

Just for reference u may pass an callback function to module1's export and then call when the file reading completes.

Module1:

var fs = require('fs');
var obj;
exports.module1= function(callback)
{
    fs.readFile('source.json', 'utf8', function (err, data)
    {
        if (err) {
            return console.error(err);
        }
        obj=JSON.parse(data);
        console.log(obj);

        callback(obj)

    });
}

Module2:

var module1 = require('./module1.js');
var obj;
module1.module1(function(result){
    obj = result;
});

var callback = function () {
    console.log(obj);
};
setTimeout(callback, 10000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM