简体   繁体   中英

Different require ways of modules in NodeJS

I'm very confusing using request modules on 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?

var app = require('express'); // like assert = require('assert')

...And about the MongoClient, Whay I can't do in the same way of router declaration?

var mongo = require('mongodb'),
    MongoClient = mongo.MongoClient();

For your first example, note that app = express() is completely different to 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM