我在Node.js中使用了一个index.js文件和一个check.js文件。我使用check.js每隔500ms检查一次数据库中的某些值是否发生了更改。如果是这样的话,变量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);发布于 2017-01-17 23:52:55
您可以将函数导出为模块。然后加载它并从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);发布于 2017-01-18 00:18:14
您可以使用全局变量。全局变量是(是的,您是对的)全局变量。
例如:
//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')https://stackoverflow.com/questions/41701263
复制相似问题