[英]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.