简体   繁体   English

如何在Node.js中的多个文件中获取变量的当前值?

[英]How can I get the current value of a variable in multiple files in Node.js?

I'm using a index.js file and a check.js file in Node.js. 我在Node.js中使用index.js文件和check.js文件。 I use check.js to check every 500 ms if some value in my databases has changed. 我使用check.js每500毫秒检查一次数据库中的某些值是否已更改。 If so, the value of variable currentInput changes. 如果是这样,变量currentInput的值将更改。 I want to use this variable currentInput in index.js so, that I get the current value of it. 我想在index.js中使用此变量currentInput,以便获取它的当前值。 I tried searching about in but the solutions I've found don't give me the current value back. 我尝试在中搜索,但是找到的解决方案并没有给我当前的价值。

In check.js: 在check.js中:

var currentInput;
.
.
.

var check = function(){
    pool.query('SELECT someValue FROM table WHERE id=1',function(err,rows){
        if(err) throw err;
        var newInput = rows[0].someValue;
        if(currentInput!=newInput){
            currentInput=newInput;
            }
        console.log('Current value:', currentInput);
    });
    setTimeout(check, 500);
}

In index.js I'd like to use it something like: 在index.js中,我想使用类似:

var x = function(currentInput);

You can export your function as a module. 您可以将功能导出为模块。 Then load it and call from index.js. 然后加载它并从index.js调用。

check.js check.js

exports.check = function() {
    pool.query('SELECT someValue FROM table WHERE id=1',function(err,rows){
        if(err) throw err;
        var newInput = rows[0].someValue;
        if(currentInput!=newInput){
            currentInput=newInput;
        }
        return currentInput);
    });  
};

index.js index.js

var check = require("./path/to/check.js");

setTimeout(function(){
    var x = check.check;
}, 500);

You can use the GLOBAL variable. 您可以使用GLOBAL变量。 The GLOBAL variable is (yes you were right) global. GLOBAL变量是(是的,您是对的)全局变量。

For example: 例如:

//set the variable
global.currentInput = newInput;
// OR
global['currentInput'] = newInput;

//get the value
var x = global.currentInput;
// OR
var x = global['currentInput'];

Note that this may not be the most efficient way of doing this, and people do not like this way at all ( https://stackoverflow.com/a/32483803/4413576 ) 请注意,这可能不是最有效的方法,人们根本不喜欢这种方法( https://stackoverflow.com/a/32483803/4413576

To use the global variable in different files, they have to be "connected with each other". 要在不同文件中使用全局变量,必须将它们“彼此连接”。

// index.js
require('./check.js')

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

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