https://nodejs.org/api/modules.html#requireid
require(id)# 添加于:v0.1.13 id 模塊名稱或路徑
回傳:匯出的模塊內容
“模塊內容”是什么意思?
const x = require('express');
const y = x();
x() 中存盤了什么?
為什么我們需要將 x 作為函式訪問并將其存盤在 y 中?
uj5u.com熱心網友回復:
模塊是一組相關代碼。
Express是一個模塊。
模塊可以匯出值(很像物件屬性有值)。
匯出的值可以是任何型別的值。
函式是一種值。
Express 匯出的值是一個函式。
您可以判斷,因為檔案告訴您將其作為函式呼叫,也可以通過查看源代碼來判斷。
uj5u.com熱心網友回復:
require(id)是用于匯入模塊的 CommonJS 語法,無論是通過它們的 npm 包名還是 js/json 檔案的路徑。當使用包名稱呼叫函式時,如"express". 在目錄中查找該包node_modules并嘗試在node_modules/express/package.json檔案中查找入口點,或者如果main未指定檔案(如 express 的情況)node_modules/express/index.js則可以使用。
在匯入之后,index.js您lib/express.js可以在其中找到主要匯出功能:
/**
* Expose `createApplication()`.
*/
exports = module.exports = createApplication;
/**
* Create an express application.
*
* @return {Function}
* @api public
*/
function createApplication() {
var app = function(req, res, next) {
app.handle(req, res, next);
};
mixin(app, EventEmitter.prototype, false);
mixin(app, proto, false);
// expose the prototype that will get set on requests
app.request = Object.create(req, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
// expose the prototype that will get set on responses
app.response = Object.create(res, {
app: { configurable: true, enumerable: true, writable: true, value: app }
})
app.init();
return app;
}
正如您在上面的代碼片段中看到的那樣,x是 expresscreateApplication函式,因為它已分配給export變數。至于為什么需要呼叫該x函式,這只是表示選擇實體化應用程式的方式,其他包的做法不同。
uj5u.com熱心網友回復:
假設您有這些檔案:
function.js:
const foo = () => console.log("Hello Word");
module.exports = foo;
index.js:
const x = require('./function');
// x == foo
x(); // will log Hello Word
這就是正在發生的事情express。Express匯出一個函式,為了使用它,您應該呼叫該函式。
如果你沒有module.exports = foo在function.js,x將等于{}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483363.html
標籤:javascript 节点.js
