1. 程式人生 > >nodejs入門基礎例項

nodejs入門基礎例項

一個完整的基於node.js的web應用

用例:

  • 使用者可以通過瀏覽器使用我們的應用。
  • 當用戶請求http://domain/start時,可以看到一個歡迎頁面,頁面上有一個檔案上傳的表單。
  • 使用者可以選擇一個圖片並提交表單,隨後檔案將被上傳到http://domain/upload,該頁面完成上傳後會把圖片顯示在頁面上。

為實現上述功能建立4個js檔案:index.js、server.js、router.js、requestHandlers.js

index.js:模擬實際專案建立的主檔案,用來呼叫應用的其他模組,node執行這個js就能啟動應用

server.js:基礎的http伺服器程式碼,建立了http伺服器;基於事件驅動的事件回撥;處理客戶端請求,將request和response作為引數傳給route(使用依賴注入的方式較鬆散地新增路由模組)。

router.js:使用url和querystring模組處理請求的路由。

requestHandlers.js:行為驅動執行,針對不同的url處理具體的業務邏輯

 

index.js

 

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/show1"] = requestHandlers.show1;

server.start(router.route, handle);

 

server.js

var http = require("http");
var url = require("url");

function start(route, handle) {
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");
        route(handle, pathname, response, request);
    }

    http.createServer(onRequest).listen(8888);
    console.log("Server has started.");
}

exports.start = start;

 

router.js

function route(handle, pathname, response, request) {
    console.log("About to route a request for " + pathname);
    if (typeof handle[pathname] === 'function') {
        handle[pathname](response, request);
    } else {
        console.log("No request handler found for " + pathname);
        response.writeHead(404, {"Content-Type": "text/html"});
        response.write("404 Not found");
        response.end();
    }
}

exports.route = route;

 

requestHandlers.js

var querystring = require("querystring"),
    fs = require("fs"),
    formidable = require("formidable");

function start(response) {
    console.log("Request handler 'start' was called.");

    var body = '<html>'+
        '<head>'+
        '<meta http-equiv="Content-Type" content="text/html; '+
        'charset=UTF-8" />'+
        '</head>'+
        '<body>'+
        '<form action="/upload" enctype="multipart/form-data" '+
        'method="post">'+
        '<input type="file" name="upload" multiple="multiple">'+
        '<input type="submit" value="Upload file" />'+
        '</form>'+
        '</body>'+
        '</html>';

    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();
}

function upload(response, request) {
    console.log("Request handler 'upload' was called.");

    var form = new formidable.IncomingForm();
    form.uploadDir='tmp';//檔案上傳 臨時檔案存放路徑
    console.log("about to parse");
    form.parse(request, function(error, fields, files) {
        console.log("parsing done");
        fs.renameSync(files.upload.path, "./tmp/text.png");
        response.writeHead(200, {"Content-Type": "text/html"});
        response.write("received image:<br/>");
        response.write("<img src='/show1' />");
        response.end();
    });
}

function show1(response) {
    console.log("Request handler 'show' was called.");
    fs.readFile("./tmp/text.png", "binary", function(error, file) {
        if(error) {
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(error + "\n");
            response.end();
        } else {
            response.writeHead(200, {"Content-Type": "image/png"});
            response.write(file, "binary");
            response.end();
        }
    });
}

exports.start = start;
exports.upload = upload;
exports.show1 = show1;

 

PS:處理程式中包括非阻塞操作就會出問題。Node.js可以在不新增額外執行緒的情況下,依然可以對任務進行並行處理——Node.js是單執行緒的,它通過事件輪詢(event loop)來實現並行操作,對此,我們應該要充分利用這一點,儘可能的避免阻塞操作,取而代之,多使用非阻塞操作。