Node.js 模組
Node.js 中的模組是什麼?
將模組視為與 JavaScript 庫相同。
一組您想包含在應用程式中的函式。
Built-in Modules
Node.js 有一套內建模組,您可以直接使用,無需額外安裝。
請參閱我們的 內建模組參考,獲取完整模組列表。
包含模組
要包含模組,請使用 `require()` 函式並傳入模組名稱。
var http = require('http');
現在您的應用程式可以訪問 HTTP 模組,並能夠建立伺服器。
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
建立自己的模組
您可以建立自己的模組,並輕鬆地將它們包含在您的應用程式中。
以下示例建立了一個返回日期和時間物件的模組。
示例
建立一個返回當前日期和時間的模組
exports.myDateTime = function () {
return Date();
};
使用 `exports` 關鍵字使屬性和方法在模組檔案外部可用。
將上面的程式碼儲存在一個名為 "myfirstmodule.js" 的檔案中。
包含自己的模組
現在您可以在任何 Node.js 檔案中包含和使用該模組。
示例
在 Node.js 檔案中使用 "myfirstmodule" 模組
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
執行示例 »
注意,我們使用 `./` 來定位模組,這意味著該模組與 Node.js 檔案位於同一資料夾中。
將上面的程式碼儲存在一個名為 "demo_module.js" 的檔案中,並執行它。
執行 demo_module.js
C:\Users\Your Name>node demo_module.js
如果您按照相同的步驟在您的計算機上操作,您將看到與示例相同的結果: https://:8080