const http = require('http'); // Node.js 內置的 http 模塊
/**
- 請求事件發生時調用的回調函數 (Node.js 是執行單線程異步非阻塞事件驅動的)
*/
function requestListener(req, rep) {
console.log("Request received."); // 當我們啟動服務器訪問網頁時, 服務器可能會輸出兩次 'Request received.', 那是因為大部分瀏覽器都會在你訪問 http://localhost:8080/ 時嘗試讀取 http://localhost:8888/favicon.ico 站點圖標
rep.writeHead(200, {'Content-Type':'text/html'}); // 響應頭
rep.write('Hello World
'); // 響應主體
rep.end(); // 完成響應
}
/**
- 創建一個基礎的 HTTP 服務器
- 請求 http 模塊提供的函數 createServer 創建一個服務器對象, 並調用該對象的 listen 方法監聽 8080 端口
- See Also:
- createServer 函數的源碼解析: https://blog.csdn.net/THEANARKH/article/details/88385964
- Node.js 是事件驅動: https://segmentfault.com/a/1190000014926921
*/
http.createServer(requestListener).listen(8080);
console.log("Server has started.");