Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
node.js-从其他文件访问所需变量_Node.js - Fatal编程技术网

node.js-从其他文件访问所需变量

node.js-从其他文件访问所需变量,node.js,Node.js,我有一个节点应用程序,它主要由两个文件组成,一个是“app.js”,另一个是“router.js”。在app.js文件中,我需要所有需要的文件,例如Redis客户端 我是一个完全的新手,我正试图弄清楚如何“访问”router.js上新创建的变量“client”: //app.js file var redis = require("redis"), client = redis.createClient(9981, "herring.redistogo.com"); app.ge

我有一个节点应用程序,它主要由两个文件组成,一个是“app.js”,另一个是“router.js”。在app.js文件中,我需要所有需要的文件,例如Redis客户端

我是一个完全的新手,我正试图弄清楚如何“访问”router.js上新创建的变量“client”:

//app.js file
var redis   = require("redis"),
    client  = redis.createClient(9981, "herring.redistogo.com");

app.get('/', routes.index);



//router.js file
exports.index = function(req, res){
 client.get("test", function(err, reply) {
   console.log(reply.toString());
 });
};
我显然得到了一个“客户端未定义”,因为它不能从router.js文件访问。我该如何解决这个问题


提前感谢。

将Redis客户端对象放入其他文件
所需的自己的文件中:

// client.js file
var redis = require("redis"),
    client = redis.createClient(9981, "herring.redistogo.com");
client.auth("mypassword");
module.exports = client;

//router.js file
var client = require("./client");
exports.index = function(req, res){
 client.get("test", function(err, reply) {
   console.log(reply.toString());
 });
};

节点中所需的模块只加载一次,每个需要该模块的文件都会获得相同的对象,因此它们都共享一个Redis客户端对象。

需要强调的是,在createClient()之后,我还需要执行以下操作:
client.auth(“mypassword”)哎哟,我得到了一个找不到的模块“./client”。。。虽然我已经在根目录中创建了该文件。可能是因为router.js在子目录中吗?@johnsmith是的,到所需模块的相对路径必须正确。听起来应该是
require('../client')在您的情况下。