Node.js來初始化HTTP協定是相當簡單的事情
下面展示一個簡單的http server範例
可以把執行路徑下的任何檔案當做http資源來瀏覽
var fs = require('fs')
, http = require('http');
http.createServer(function (req, res) { var path = req.url;
try{
var f = fs.readFileSync('.' + path);
console.log(f);console.log(f);
res.end(f.toString()); } catch(e) {
console.log(e);
res.end('');
}}
}).listen(1337); console.log('Server running at http://127.0.0.1:1337/');目前作者已經包裝成NPM套件可以透過下面方式安裝與使用(以下擷取自:https://github.com/peihsinsu/noder)Noder - Simple HTTP Server
Install
Install using npm...# npm install noder -g
Usage
# noder Server running at http://127.0.0.1:1337/View
Browser View http://127.0.0.1:1337/test.html (Assump that the test.html exist in the current folder)<Buffer 23 21 2f 62 69 6e 2f 62 61 73 68 0a 63 64 20 2f 6f 70 74 0a 23 77 67 65 74 20 68 74 74 70 3a 2f 2f 6e 6f 64 65 6a 73 2e 6f 72 67 2f 64 69 73 74 2f 76 30 ...> { [Error: ENOENT, no such file or directory './favicon.ico'] errno: 34, code: 'ENOENT', path: './favicon.ico', syscall: 'open' } <Buffer 1f 8b 08 00 ed 18 e5 50 00 03 ec 3d 6b 77 db 36 b2 f9 5a fd 0a 44 67 cf 4a 4a 25 ea 2d 77 ed 3a 8d 9b b8 4d 77 f3 ba b1 fb b8 27 37 c7 a2 48 c8 62 4c 91 ...>