简体   繁体   中英

Node.js access var issue

My project structure is the following:

project
   - js
      - *.js
app.js

In my app.js , I define a config variable this way:

try {
    var config = yaml.load(program.config);
} catch (e) {
    console.error('unable to load configuration, Error:', e.message);
    process.exit(1)
}

Which works.
I now would like to access to the content of the var in project/js/*.js , but I got config is undefined .
Why? Isn't config not supposed to be accessible everywhere?

** EDIT **

My code in *.js :

var fetchMail = function() {

    console.log(config); // config undefined
    // Other stuff
}; 

And how I export my code in app.js : export.config = config . And then require it in *.js : var app = require(../app);

I assume you need to change export.config = config to exports.default = config .

If you are exporting something else than exports.config = config .

In other file you need either

import { config } from ..

or

var config = require(...).config;

You should put var config = null on top of try and you than can access the config variable. Initializing var inside try will create the variable inside that scope. Therefore, you can't be accessing config variable.

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