在Node.js文件之间共享变量? [英] Share variables between files in Node.js?

查看:454
本文介绍了在Node.js文件之间共享变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有两个文件:

  // main.js 
require('./ modules');
console.log(name); //打印foobar

// module.js
name =foobar;

当我没有var时,它可以工作。但是,当我有:

  // module.js 
var name =foobar;

名称将在main.js中未定义。



我听说全局变量很糟糕,你最好在引用之前使用var。但是,这是全局变量好吗?

解决方案

全局变量几乎 事情(也许是一个例外或两个在那里......)。在这种情况下,它看起来像你真的只想导出你的名称变量。例如,

  // module.js 
var name =foobar;
//导出
exports.name = name;

然后,在main.js中...

  // main.js 
//获取所需模块的引用
var myModule = require('./ module');

//由于
以上的输出,name是myModule的成员var name = myModule.name;


Here are 2 files:

// main.js
require('./modules');
console.log(name); // prints "foobar"

// module.js
name = "foobar";

When I don't have "var" it works. But when I have:

// module.js
var name = "foobar";

name will be undefined in main.js.

I have heard that global variables are bad and you better use "var" before the references. But is this a case where global variables are good?

解决方案

Global variables are almost never a good thing (maybe an exception or two out there...). In this case, it looks like you really just want to export your "name" variable. E.g.,

// module.js
var name = "foobar";
// export it
exports.name = name;

Then, in main.js...

//main.js
// get a reference to your required module
var myModule = require('./module');

// name is a member of myModule due to the export above
var name = myModule.name;

这篇关于在Node.js文件之间共享变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆