博客
关于我
Node.js初体验
阅读量:795 次
发布时间:2023-02-16

本文共 4573 字,大约阅读时间需要 15 分钟。

Node.js异步处理与事件驱动模式

前言

刚刚阅读了《Node.js入门》,参考node官网和一些相关文章,感觉与Node.js更亲近了一步。迫不及待想写篇文章分享,希望读者能读完后获益良多。

应用目标

• 用户可以通过浏览器使用我们的应用。

• 当用户提交文件时,看到一个欢迎页面,包含一个文件上传表单。

• 用户选择图片提交后,图片将上传到服务器,并在页面上显示。

实现思路

首先,搭建Node.js服务器。Node.js可以通过http模块轻松创建服务器。创建路由模块,将不同请求路由到相应的处理程序。

应用实现

运行Node.js

创建一个简单的helloworld.js文件:

console.log("Hello World");

在终端运行:

node helloworld.js

输出:Hello World

创建服务器

创建server.js文件:

var http = require("http");http.createServer(function(request, response) {    response.writeHead(200, {"Content-Type": "text/plain"});    response.write("Hello World");    response.end();}).listen(8888);console.log("Server has started.");

运行:

node server.js

输出:Server has started.

加入路由

创建router.js:

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

创建requestHandlers.js:

function start() {    console.log("Request handler 'start' was called.");}function upload() {    console.log("Request handler 'upload' was called.");}module.exports = { start, upload };

创建index.js:

var server = require("./server");var router = require("./router");var requestHandlers = require("./requestHandlers");var handle = {};handle["/"] = requestHandlers.start;handle["/upload"] = requestHandlers.upload;server.start(router.route, handle);

运行:

node index.js

输出:Server has started.

异步处理

阻塞响应

修改requestHandlers.js:

function start() {    console.log("Request handler 'start' was called.");    function sleep(milliSeconds) {        var startTime = new Date().getTime();        while (new Date().getTime() < startTime + milliSeconds) {}    }    sleep(10000);    return "Hello Start";}function upload() {    console.log("Request handler 'upload' was called.");    return "Hello Upload";}module.exports = { start, upload };
非阻塞响应

修改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);        response.write(content);        response.end();    }    http.createServer(onRequest).listen(8888);    console.log("Server has started.");}module.exports = start;

修改route.js:

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

修改requestHandlers.js:

function start(response) {    console.log("Request handler 'start' was called.");    var content = "empty";    var exec = require("child_process").exec;    exec("find /", { timeout: 10000, maxBuffer: 20000 * 1024 }, function (error, stdout, stderr) {        content = stdout;        response.writeHead(200, {"Content-Type": "text/plain"});        response.write(content);        response.end();    });}function upload(response) {    console.log("Request handler 'upload' was called.");    response.writeHead(200, {"Content-Type": "text/plain"});    response.write("Hello Upload");    response.end();}module.exports = { start, upload };

运行:

node index.js

文件上传

使用formidable模块:

var formidable = require('formidable');var http = require('http');var fs = require('fs');http.createServer(function(req, res) {    if (req.url === '/upload' && req.method.toLowerCase() === 'post') {        var form = new formidable.IncomingForm();        form.parse(req, function(err, fields, files) {            fs.readFile(files.upload.path, 'binary', function(err, file) {                if (err) {                    res.writeHead(500, {"Content-Type": "text/plain"});                    res.write(err + '\n');                    res.end();                } else {                    res.writeHead(200, {"Content-Type": "image/png"});                    res.write(file, 'binary');                    res.end();                }            });        });        return;    }    res.writeHead(200, {"Content-Type": "text/html"});    res.end('
');}).listen(8888);console.log("Server has started.");

结语

通过以上步骤,我们成功创建了一个异步处理的文件上传应用。Node.js的异步特性使得服务器能够高效处理大量请求,适合构建高性能的网络应用。

转载地址:http://mpjfk.baihongyu.com/

你可能感兴趣的文章