2014年5月

nodejs(三)

  嗯,这次的任务是完成一个带图片上传的表单处理程序,然后将图文在浏览器中显示出来。我们需要处理3个请求,分别是start、upload、show。所以先修改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["/show"] = requestHandlers.show; //展示图片用
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 running");
}
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') {
        //执行对应的handler并且传入响应和请求
        handle[pathname](response, request);
    } else {
        //如果没有对应的requestHandler的话,返回404.
        console.log("No request handle found for " + pathname);
        response.writeHead(404, {"Content-Type": "text/plain"});
        response.write("404 Not Found");
        response.end();
    }
}
exports.route = route;

关键部分requestHandlers.js来了。在这里,我们使用了一个包/模块来专门处理post数据。

npm install formidable 安装成功后就能使用formidable模块了。

requestHandler.js代码如下:

var fs = require("fs");//引入文件读取模块
var formidable = require("formidable");//引入我们下载的formidable模块

function start(response, request) {
    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" method="post" enctype="multipart/form-data">'+
                    '<textarea name="text" rows="20" cols="60"></textarea>'+
                    '<input type="file" name="upload" />'+
                    '<input type="submit" value="Submit" />'+
                '</form>'+
                '</body>'+
                '</html>';
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);//创建一个form表单,显示在浏览器中
    response.end();
}

function upload(response, request) {
    console.log("Request handler 'upload' was called.");
    //使用fromidable模块读取表单数据
    var form = new formidable.IncomingForm();
    //解析请求里面的数据,反回fields、files数据
    form.parse(request, function(error, fields, files) {
        console.log("parsing done");
        //把图片从临时文件夹移动到当前文件夹并重新命名
        fs.renameSync(files.upload.path, "./test.png");
        response.writeHead(200, {"Content-Type" : "text/html"});
        //显示表单中文字字段"text"的内容
        response.write("text: "+ fields.text);
        //图片通过show函数显示
        response.write("<img src='./show' />");
        response.end();
    });
}

function show(response) {
    console.log("Request handler 'show' was called.");
    //读取test.png,读取成功就反回二进制数据。
    fs.readFile("./test.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.show = show;

最后,还是 $ node index.js

尽情享受吧。

nodejs(二)

  上一篇文章谈了一些基本的nodejs,这次学写“路由器”,首先加入新的模块requestHandlers.js。这个模块里面可以处理两个请求,分别是start和upload,并各自向浏览器返回了一些字符串。

function start() {
    console.log("Request handler 'start' was called.");
    return "Hello Start";//在浏览器上显示
}

function upload() {
    console.log("Request handler 'upload' was called.");
    return "Hello Upload";
}
exports.start = start;
exports.upload = upload;

  处理请求的模块好了,我们这是总需要一个路由器吧,不然怎么把请求分配到对应的函数上呢?所以router.js应运而生。

function route(handle, pathname) {
    console.log("About to route a request for" + pathname);
    if (typeof handle[pathname] === 'function') {
        return handle[pathname]();
    } else {
        console.log("No request handle found for " + pathname);
        return "404 Not found";
    }
}
exports.route = route;

  以上代码,先检查给定的路径对应的请求处理程序是否存在(即requestHandlers.js中是否存在),如果存在的话直接调用相应的函数。我们可以用从关联数组中获取元素一样的方式从传递的对象中获取请求处理函数,因此就有了简洁流畅的形如handle\[pathname\]();的表达式,这个感觉就像在前方中提到的那样:“请帮我处理了这个路径”。

  然后就是改写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.");
        response.writeHead(200, {
            "Content-Type": "text/plain"
        });
        var content = route(handle, pathname);//在此处开启路由
        response.write(content);//在浏览器输出对应函数返回的字符串
        response.end();
    }

    http.createServer(onRequest).listen(8888);
    console.log("Server running");
}
exports.start = start;

最后修改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;
server.start(router.route, handle);

最后 > node index.js

我们就可以在浏览器输入:

http://localhost/

http://localhost/start

http://localhost/upload

http://localhost/1234

看到不同的结果了。

nodejs(一)

  Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven(事件驱动), non-blocking I/O model(无锁I/O模型) that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

  首先是从官网(http://nodejs.org/)下载对应的系统版本,然后安装,设置环境path。

  找个地方作为工作区,建立example.js。

var http = require('http');

http.createServer(function (request, response) {
    console.log('Request received.');
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
}).listen(8080);

  console.log('Server running at http://127.0.0.1:8080');
其中匿名函数作为createServer的参数,匿名函数有两个参数,request和response,即请求和响应。然后在收到请求后返回http头信息和"hello world"。listen监听8080端口,最后一行打印server运行状态。而这个过程是异步的。

  在我们在终端运行 > node example.js 时,会显示 Server running at 。。。 表示运行到最后一行了。而当我们浏览器访问http://localhost:8080时,会显示hello world。而终端里显示出Request received。这个结果就是因为nodejs是异步的和基于事件驱动的,很好理解。

  再来一个例子: server.js

var http = require("http");

function start() {
    function onRequest(request, response) {
        console.log("Request received.");
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write("Hello world.");
        response.end();
    }

    http.createServer(onRequest).listen(8080);
    console.log("Server has started.");
}
exports.start = start

  主文件:index.js

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

server.start();

在终端里运行 > node index.js

  会出来和上一个例子一样的结果。这里 server.js就是一个模块。模块的作用就是启动一个server。onRequest作为一个函数传递给了http模块的createServer方法。用export导出start外部才可以使用。

  我觉得简单,也很有趣。