Node入门的一本电子书

Node入门

本书最后实现了一个简易Node应用,对于入门Node的同学,理解模块、阻塞、事件驱动等概念有很大帮助。

server.js

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

function start(route,handler) {
    function onRequest(req,res) {
        var postData = "";

        var pathname = url.parse(req.url).pathname;
        console.log("Request for " + pathname + " received.");
        
        if (pathname === "/favicon.ico") return;    

        route(handler,pathname,res,req);
    }

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

exports.start = start;

router.js

function route(handle,pathname,res,req) {
    console.log("About to route a request for " + pathname);

    if (typeof handle[pathname] === "function") {
        return handle[pathname](res,req);
    } else {
        console.log("Error! No request handler found for " + pathname);
    }

}

exports.route = route;

reqHandlers.js

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

function start(res) {
    console.log("Request handler 'start' was called.");
  
    var body = '' +
        '' +
        '' +
        '' +
        '' +
        '
' + '' + '' + '
' + '' + ''; res.writeHead(200,{"Content-Type":"text/html"}); res.write(body); res.end(); } function upload(res,req) { console.log("Request handler 'upload' was called."); // 可以试着打印req对象,查看如何解析的 var form = new formidable.IncomingForm(); console.log("form 正在解析 post"); form.parse(req,function(error,fields,files) { console.log("解析完成"); // 重命名图片,确保show正确 console.log(files.upload.path); fs.renameSync(files.upload.path, "./tmp/test.png"); res.writeHead(200, {"Content-Type": "text/html"}); res.write("received image:
"); res.write(""); res.end(); }) } function show(res) { console.log("Request handler 'show' was called"); fs.readFile("./tmp/test.png","binary",function(error,file) { if (error) { res.writeHead(500, {"Content-Type": "text/plain"}); res.write(error + "\n"); res.end(); } else { res.writeHead(200, {"Content-Type": "image/png"}); res.write(file, "binary"); res.end(); } }) } exports.start = start; exports.upload = upload; exports.show = show;

main.js

var server = require("./server");
var router = require("./router");
var reqhandlers = require("./reqHandlers");

var handler = {};
handler["/"] = reqhandlers.start;
handler["/start"] = reqhandlers.start;
handler["/upload"] = reqhandlers.upload;
handler["/show"] = reqhandlers.show;

server.start(router.route,handler);

你可能感兴趣的:(Node入门的一本电子书)