2013-01-30

NodeJS 簡單的 HTTP Server

底下的範例在啟動之後自動指定同一資料夾為 HTTP Server 之根目錄:
var http = require('http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');
 
var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"};
 
http.createServer(function(req, res) {
    var uri = url.parse(req.url).pathname;
    console.log(uri);
    var empty =function(){
        res.writeHead(200, {'Content-Type': 'text/plain'});     
        res.end();
    };
    if (uri ==='/'){
        return empty();
    };
    var filename = path.join(process.cwd(), uri);
    fs.exists(filename, function(exists){
        if(!exists || fs.lstatSync(filename).isDirectory()===true){
            return empty();
        }
        res.writeHead(200, {
            'Content-Type':mimeTypes[path.extname(filename).split(".")[1]]
        });
        fs.createReadStream(filename).pipe(res);
    }); //end fs.exists
}).listen(8080);
在同一資料夾裡擺一個檔案 (index.html),啟動之後利用網址 http://localhost:8080/index.html 即可瀏覽該檔案。