简体   繁体   English

Nodejs:跨多个文件的全局变量

[英]Nodejs: Global variables across multiple files

I have written my code across several files for my node server.我已经为我的节点服务器编写了跨多个文件的代码。

If I have a file, say basket.js:如果我有一个文件,请说basket.js:

var Basket = {
    fruits : 0,
    
    addFruit : function() {
        fruits++;
    },

    removeFruit : function() {
        fruits--;
    },

    printFruit : function() {
        console.log(this.fruits);
    }
}
module.export = Basket;

And I have another file called give.js:我还有另一个名为 give.js 的文件:

var Basket1 = require("./basket.js");

Basket1.addFruit();
Basket1.printFruit();

And another file called take.js:另一个名为 take.js 的文件:

var Basket2 = require("./basket.js");

Basket2.removeFruit();
Basket2.printFruit();

Will both files write into the same instance of Basket?两个文件会写入同一个篮子实例吗? In other words, will they both have control over the property, fruits?换句话说,他们会控制财产,水果吗? Does node manage race conditions on its own?节点是否自行管理竞争条件? ie if two commands to modify fruit come in at the same time from add and sub, does node know how to handle it?即如果两个修改水果的命令同时从 add 和 sub 进来,node 知道如何处理吗?

If I want to make a way in which two files can look at a singleton at the same time and access it, is this the way to go??如果我想使两个文件可以同时查看一个单例并访问它,这是要走的路吗? Or how else does one do it?或者其他人如何做到这一点?

Yes, they will access the same object.是的,他们将访问同一个对象。

Modules are cached after the first time they are loaded.模块在第一次加载后被缓存。 This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.这意味着(除其他外)每次调用 require('foo') 都会返回完全相同的对象,如果它解析为相同的文件。

Modules docs 模块文档

No, node does not manage race conditions on its own, because race conditions will not be caused by node itself.不,节点不会自行管理竞争条件,因为竞争条件不会由节点本身引起。 Node is single-threaded and thus no code can be executed at the same time as other code. Node 是单线程的,因此任何代码都不能与其他代码同时执行。 See for example this answer for some more explanation.例如,请参阅此答案以获取更多解释。

我是初学者,但我认为正确的语法是module.exports而不是modules.export - 如果您可以纠正,那么人们就不会想知道为什么它不像我刚才那样工作:)

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

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