首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Node.js中获取多个文件中一个变量的当前值?

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

Stack Overflow用户
提问于 2017-01-17 23:40:20
回答 2查看 181关注 0票数 0

我在Node.js中使用了一个index.js文件和一个check.js文件。我使用check.js每隔500ms检查一次数据库中的某些值是否发生了更改。如果是这样的话,变量currentInput的值就会改变。我想在index.js中使用这个变量currentInput,这样我就可以得到它的当前值。我尝试在中搜索,但我找到的解决方案没有返回当前值。

在check.js中:

代码语言:javascript
复制
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中,我想使用它,类似于:

代码语言:javascript
复制
var x = function(currentInput);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-17 23:52:55

您可以将函数导出为模块。然后加载它并从index.js调用。

check.js

代码语言:javascript
复制
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

代码语言:javascript
复制
var check = require("./path/to/check.js");

setTimeout(function(){
    var x = check.check;
}, 500);
票数 0
EN

Stack Overflow用户

发布于 2017-01-18 00:18:14

您可以使用全局变量。全局变量是(是的,您是对的)全局变量。

例如:

代码语言:javascript
复制
//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)

要在不同的文件中使用全局变量,它们必须“相互连接”。

代码语言:javascript
复制
// index.js
require('./check.js')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41701263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档