Node.js - 03 模組
JavaScript
什麼是 Node.js 模組?
可以將模組視為與 JavaScript 函式庫相同。
內建模組
導入模組
使用 require( ) 包含模組名稱 :
var http = require('http');
建立自己的模組
建立一個檔案名為 “myfirstmodule.js”。這是一個回傳日期、時間的模組 :
exports.myDateTime = function () { return Date(); };
使用 “exports” 關鍵字,讓屬性、方法可以在檔案外部使用。
導入模組
建立一個新檔案 “demo_module.js”。
現在可以導入剛剛建立的模組 “myfirstmodule.js”。
現在可以導入剛剛建立的模組 “myfirstmodule.js”。
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 demo_module.js
應該會看到目前的時間:
![](/rails/active_storage/representations/redirect/eyJfcmFpbHMiOnsiZGF0YSI6IjYyMzE0OTNhLTU4MmQtNDY3ZS05ZjJmLWRhY2I5ZDBkYjIxYyIsInB1ciI6ImJsb2JfaWQifX0=--564088c66ff75b9216f45b6f7da74c6c419e0052/eyJfcmFpbHMiOnsiZGF0YSI6eyJmb3JtYXQiOiJwbmciLCJsb2FkZXIiOnsibiI6LTF9LCJyZXNpemVfdG9fbGltaXQiOlsxMDI0LDc2OF19LCJwdXIiOiJ2YXJpYXRpb24ifX0=--589eab3cb219aa7003ba9652c21b627759a6f0bb/image.png)