Javascript 如何在Node.js的多个文件中获取变量的当前值?
我在Node.js中使用index.js文件和check.js文件。我使用check.js每500毫秒检查一次数据库中的某个值是否发生了变化。如果是,则变量currentInput的值会发生变化。我想在index.js中使用这个变量currentInput,以便获得它的当前值。我尝试在中搜索,但找到的解决方案没有返回当前值 在check.js中:Javascript 如何在Node.js的多个文件中获取变量的当前值?,javascript,node.js,Javascript,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 som
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);
您可以使用全局变量。全局变量是全局变量(是的,你是对的) 例如:
//set the variable
global.currentInput = newInput;
// OR
global['currentInput'] = newInput;
//get the value
var x = global.currentInput;
// OR
var x = global['currentInput'];
请注意,这可能不是最有效的方法,而且人们根本不喜欢这种方法()
要在不同的文件中使用全局变量,它们必须“相互连接”
check.js是一个模块吗?如何初始化“检查”功能?如果它是作为一个模块来完成的,那么对currentInput值进行限定应该相对容易,这样父级(index.js)就可以访问它。我删除了
if(currentInput!=newInput){currentInput=newInput;}
并将其更改为回调(newInput)
,并将设置超时
放入index.js。但是,在某些值上它工作得很好,在其他值上我得到错误throw err;//Rethow非MySQL错误
后跟类型错误:无效的十六进制字符串
。这可能是什么原因造成的?@krishann_u将查询直接运行到您的SQL server中,以查看您得到的响应。我不知道你的功能是什么,告诉你为什么会出现这个错误。摆脱这个错误。我在index.js文件中创建了一个缓冲区
,其中包含了我想从checker.js使用的变量值。我已经将该缓冲区放在try/catch块中,现在我可以使用以前不起作用的值。这个错误似乎与我的SQL server没有任何关系
// index.js
require('./check.js')