[英]Different require ways of modules in NodeJS
I'm very confusing using request modules on nodeJS. 我在nodeJS上使用请求模块非常困惑。 I can´t understand the following foundation about the many manners to require this modules. 我无法理解以下有关要求此模块的多种方式的基础。
This snipet that's correct but, Why has it to be in this way? 这个片段是正确的,但是,为什么要这样呢?
var express = require('express'),
app = express(),
router = express.Router(),
assert = require('assert'),
MongoClient = require('mongodb').MongoClient;
For example, assert
have methods and express
too, so, why it can't be declared directly in the app
variable? 例如, assert
具有方法并且也可以express
,那么,为什么不能直接在app
变量中声明它?
var app = require('express'); // like assert = require('assert')
...And about the MongoClient, Whay I can't do in the same way of router
declaration? ...关于MongoClient,我不能以相同的方式声明router
吗?
var mongo = require('mongodb'),
MongoClient = mongo.MongoClient();
For your first example, note that app = express()
is completely different to app = express
. 对于第一个示例,请注意app = express()
与app = express
完全不同。 The former assigns the result of calling a function, while the latter is equivalent to your suggestion that won't work. 前者分配调用函数的结果,而后者则等同于您的建议,将不起作用。 You could do the following if you really like repetition, but then you won't have a reference to the express
module: 如果您确实喜欢重复,可以执行以下操作,但是您将没有对express
模块的引用:
var app = require('express')(),
router = require('express').Router()
For your second example, again you're confusing assignment of a function with assignment of the result of a function call. 对于第二个示例,再次将函数的分配与函数调用的结果的分配相混淆。 A correct (but with an unnecessary extra line) alternative would be: 正确的(但有不必要的多余行)替代方法是:
var mongo = require('mongodb'),
MongoClient = mongo.MongoClient
In short there's only one way to require a module - require('nameOrPath')
- everything else is unrelated to the module system. 简而言之,只有一种需要模块require('nameOrPath')
-其他所有与模块系统无关的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.