須要引用 http 模塊,http 模塊是 node.js 的內置模塊。node
var http = require('http'); http.createServer(function(request, response) { console.log('Request received...'); response.writeHead({'Content-type': 'text/plain'}); response.write('Hello node.js'); response.end(); }).listen(8888); console.log('server start...');
保存以上代碼爲 server.js,打開終端(能夠是 cmd)經過 node 運行 server.js,固然前提是先要進入 server.js 所在的目錄。瀏覽器
node server
瀏覽器打開 http://localhost:8888/ 能夠看到頁面上顯示 Hello node.js 。服務器
切換到終端,能夠看到輸出了一些東西:模塊化
server start...
Request received...
Request received...
請注意,當咱們在服務器訪問網頁時,咱們的服務器可能會輸出兩次 Request received...
。那是由於大部分服務器都會在你訪問 http://localhost:8888/ 時嘗試讀取 http://localhost:8888/favicon.ico。函數
編寫稍大一點的程序時通常都會將代碼模塊化。在 nodejs 中,通常將代碼合理拆分到不一樣的 js 文件中,每個文件就是一個模塊,而文件名稱就是模塊名。ui
那麼如何把 server.js 封裝成模塊?很簡單,看下面代碼:spa
var http = require('http'); function start() { function onRequest(request, response) { console.log('request received...'); response.writeHead({ 'Content-type': 'text/plain' }); response.write('Hello node.js'); response.end(); } http.createServer(onRequest).listen(8888); console.log('server start...'); } exports.start = start;
以上代碼就是將 server.js 封裝爲模塊了,而且導出 start 方法。code
exports
是當前模塊的導出對象,用於導出當前模塊的公有方法和屬性。server
其實在 server.js 中,就已經學會了如何引用模塊以及使用模塊的方法:對象
var http = require('http'); // 引用 http 模塊 http.createServer(); // 調用 http 模塊的方法
require
函數用於在當前模塊中加載和使用別的模塊,傳入一個模塊名,返回一個模塊導出對象(exports
)。模塊名可以使用相對路徑(以 ./
開頭),或者是絕對路徑(以 /
或 c:
之類的盤符開頭)。另外,模塊名中的 .js
擴展名能夠省略。
新建主文件 index.js 文件(與 server.js 同級),在 index.js 中啓動 http 服務器:
var server = require('./server'); server.start();
在終端啓動服務:
node index
瀏覽器打開 http://localhost:8888/ 能夠看到頁面上顯示 Hello node.js,OK,和以前同樣。
這樣構建一個基礎的 http 服務器就完成了。