访问模块中的对象

Access to object in module

我正在做一些将 json 数据解析为对象的逻辑,我想在其他模块可以使用的某些模块特定对象之外公开, 我尝试了以下方法,但没有用,还有其他想法吗?

var jsonObject;

module.exports = {

    parse: function () {
    //here I do the parsing
    ....

    jsonObject = JSON.parse(res)

    ,
    //here I want to expose it outside
    jsonObj:jsonObject
    }

如果你试图公开整个对象,你可以像构建任何其他 JavaScript 对象一样构建它,然后在最后使用 module.exports :

MyObj = function(){
   this.somevar = 1234;
   this.subfunction1 = function(){};
}
module.exports = MyObj;

如果您只想公开某些功能,则不需要像对象一样构建它,然后您可以导出各个功能:

var somevar = 1234;
subfunction1 = function(){};
nonExposedFunction = function(){};
module.exports = {
   subfunction1:subfunction1,
   somevar:somevar
};

您只需将 JSON.parse 的结果分配给 this.jsonObj:

module.exports = {
    parse: function (res) {
        this.jsonObj = JSON.parse(res);
    }
};

使用 this.jsonObj 您将 JSON 对象暴露给外部,您可以这样使用您的模块:

var parser = require('./parser.js'),
    jsonString = // You JSON string to parse...

parser.parse(jsonString);
console.log(parser.jsonObj);