我有这个代码(效果非常好),我从在线资源中借用了这些代码:
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var app = express();
require('./init/db');
require('./init/cache'); //Bring in Redis
//Define Routes
var userRoutes = require('./routes/user');
module.exports = app;
Run Code Online (Sandbox Code Playgroud)
当我以这种方式使用时,我不明白的是"要求"?这是它带来的文件:
//db.js
var mongoose = require('mongoose');
var dbURI = <theURI>;
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected successfully');
});
Run Code Online (Sandbox Code Playgroud)
我的Redis连接也一样:
//cache.js
var redis = require("redis");
var redisClient = redis.createClient(process.env.CACHE_PORT, process.env.CACHE_URL);
redisClient.auth(process.env.CACHE_PASS);
redisClient.on("ready", function () {
console.log("Cache is connected");
});
Run Code Online (Sandbox Code Playgroud)
但正如你所看到module.exports的db.js,cache.js文件中没有任何地方!当我谷歌这一点来了解它是如何工作的时候,这些例子总是在谈论module.exports和require共同.
问题
当有人这样使用时,有人可以解释一下需要如何工作吗?
如何使缓存/ Redis连接可用,以便可以使用以下内容在我的userRoutes文件中使用它:var userRoutes = require('./routes/user')(redis);
Dro*_*own 47
有人可以解释这段代码发生了什么吗?换句话说,当不与导出一起使用时,如何工作.
我们几乎总是看到require()被使用module.exports,但你没有必要.如果不导出任何内容,导入模块中的代码仍将运行,但您无法将导入绑定到变量并与之交互.
考虑以下Foo.js模块:
var foo = {};
foo.greet = function(){
console.log('Hello from Foo!');
}
foo.greet();
Run Code Online (Sandbox Code Playgroud)
我可以在我的主文件中导入这个模块,如下所示:
require('./foo');
Run Code Online (Sandbox Code Playgroud)
如果我运行这个主文件,Foo.js模块中的代码将运行,而来自Foo的Hello!将打印到控制台.
但是,我无法直接与foo对象进行交互.以下代码不起作用:
require('./foo');
foo.greet(); //ReferenceError, foo is not defined
Run Code Online (Sandbox Code Playgroud)
我可以将模块导入绑定到变量,但即使这样也行不通:
var foo = require('./foo');
foo.greet(); //TypeError, foo.greet is not a function
Run Code Online (Sandbox Code Playgroud)
为了使它工作,我需要使用module.exports你熟悉的模块从我的模块中导出foo对象.
这表明您不需要从模块中导出任何内容,就像您不需要在需要时将导入的模块绑定到变量一样.不同之处在于,如果不导出不希望在该模块中显示的内容,则无法与导入模块中的代码进行交互.
在您的问题的代码中,导入Redis是有效的,因为该模块是自包含的,您不需要在代码中与它进行交互.您只需要导入代码以便它可以运行(需要主Redis模块并创建客户端)
除了需要一个不包含导出的模块来运行它的副作用外,该模块还可以在全局范围内定义变量,这些变量可以在需要该模块的文件中进行访问。这是通过定义不带var关键字的变量来实现的。这不是一个好习惯,但是您可能会在某个地方遇到它,因此最好知道发生了什么。
例:
// foo.js
bar = 5;
Run Code Online (Sandbox Code Playgroud)
和
// test.js
require('./foo');
console.log(bar);
// prints 5
Run Code Online (Sandbox Code Playgroud)
如果bar定义为:
var bar = 5;
Run Code Online (Sandbox Code Playgroud)
它在模块范围内,无法在中访问test.js。
| 归档时间: |
|
| 查看次数: |
12614 次 |
| 最近记录: |