簡體   English   中英

如何在Node.js中的多個文件中獲取變量的當前值?

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

我在Node.js中使用index.js文件和check.js文件。 我使用check.js每500毫秒檢查一次數據庫中的某些值是否已更改。 如果是這樣,變量currentInput的值將更改。 我想在index.js中使用此變量currentInput,以便獲取它的當前值。 我嘗試在中搜索,但是找到的解決方案並沒有給我當前的價值。

在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);
}

在index.js中,我想使用類似:

var x = function(currentInput);

您可以將功能導出為模塊。 然后加載它並從index.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

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

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

您可以使用GLOBAL變量。 GLOBAL變量是(是的,您是對的)全局變量。

例如:

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

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

請注意,這可能不是最有效的方法,人們根本不喜歡這種方法( https://stackoverflow.com/a/32483803/4413576

要在不同文件中使用全局變量,必須將它們“彼此連接”。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM