简体   繁体   English

Node.js访问var问题

[英]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: 在我的app.js ,我以这种方式定义了一个配置变量:

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 . 我现在想访问project/js/*.js var的内容,但是我得到的config is undefined
Why? 为什么? Isn't config not supposed to be accessible everywhere? config不应该在任何地方都不能访问吗?

** EDIT ** **编辑**

My code in *.js : 我在*.js代码:

var fetchMail = function() {

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

And how I export my code in app.js : export.config = config . 以及如何在app.js导出代码: export.config = config And then require it in *.js : var app = require(../app); 然后在*.js要求它: var app = require(../app);

I assume you need to change export.config = config to exports.default = config . 我假设您需要将export.config = config更改为exports.default = config

If you are exporting something else than exports.config = config . 如果要导出的东西不是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. 您应该将var config = null放在try之上,然后您可以访问config变量。 Initializing var inside try will create the variable inside that scope. 在try内部初始化var将在该范围内创建变量。 Therefore, you can't be accessing config variable. 因此,您不能访问config变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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