2015-10-15 80 views

回答

1

require() statement從正在加載的模塊中返回module.exports屬性。你所做的完全取決於模塊設置的內容。

如果模塊將其設置爲某種(通常稱爲模塊構造函數)的函數,那麼很自然的與var something = require('xxx')(...);

叫它但是,如果模塊只是出口對象具有的屬性就可以了,那麼嘗試調用它實際上是一個編程錯誤。

那麼,它完全取決於你正在加載的模塊是在輸出。


例如,加載文件系統模塊時,這純粹是:

var fs = require('fs'); 

在這種情況下,變量fs只是一個對象(不是函數),所以你不會把它 - 你只是引用它的屬性:

fs.rename(...) 

這裏有一個模塊的出口爲例一個構造函數,你會後與()撥打:

// myRoutes.js 
module.exports = function(app) { 
    app.get("/", function() {...}); 
    app.get("/login", function() {...}); 
} 

// app.js 

// other code that sets up the app object 
// .... 

// load a set of routes and pass the app object to the constructor 
require('./myRoutes')(app); 

而且,這裏有一個模塊只導出屬性,這樣你就不會調用模塊本身就是一個例子:

// myRoutes.js 
module.exports.init = function(app) { 
    app.get("/", function() {...}); 
    app.get("/login", function() {...}); 
} 

// export commonly used helper function 
module.exports.checkPath = function(path) { 
    // .... 
} 

// app.js 

// other code that sets up the app object 
// .... 

// load a set of routes and then initialize the routes 
var routeStuff = require('./myRoutes'); 
routeStuff.init(app); 


if (routeStuff.checkPath(somePath)) { 
    // ... 
} 
相關問題