小小少年

书山有路勤为径,学海无涯苦作舟

Node之从入门到高级入门

概述

本文主要利用node搭建服务器,配置路由,处理请求,最终实现了图片上传及在浏览器中展示功能。

功能模块

  • index.js 入口文件
  • server.js 服务器搭建
  • routes.js 配置路由
  • requestHandles.js 处理请求

架构梳理

  1. indes.js作为入口文件,配置不同路由的请求处理函数;并把touter和handler处理函数对象传递给 server.js
  2. server.js 响应请求,把请求&响应数据&处理函数传递给 router.js;
  3. router.js 根据传递的路由,路径进行调用 handler处理函数
  4. requestHandles.js 定义不同路由的处理函数

知识点

  1. 模块分离
  2. 利用child_process 非阻塞模型
  3. 表单处理包formidable

index.js同级目录下新建tmp文件夹。
运行 npm install formidable; node indes.js

index.js
var server = require('./server.js');
var router = require('./router.js');
var requestHandles = require('./requestHandles');
var handle = {};
handle['/'] = requestHandles.start;
handle['/start'] = requestHandles.start;
handle['/upload'] = requestHandles.upload;
handle['/show'] = requestHandles.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 postData = '';
        var pathname = url.parse(request.url).pathname;
        console.log('request for ' + pathname + ' recevied');
        request.setEncoding('utf8');
        request.addListener('data', function(postDataChunk) {
            postData += postDataChunk;
            console.log("Received POST data chunk '" +
                postDataChunk + "'.");
        })
        request.addListener('end', function() {
            route(handle, pathname, response, postData);
        })
    }
    http.createServer(onRequest).listen(8888);
    console.log('server start');
}*/
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;
routes.js
/*function route(handle, pathname, response, postData) {
    console.log('about to route a request for ' + pathname);
    if (typeof handle[pathname] === 'function') {
        handle[pathname](response, postData);
    } else {
        console.log('not request handler found for ' + pathname);
        response.writeHead(404, { "Content-Type": "text/plain" });
        response.write('404 not found');
        response.end();
    }
}*/
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;

requestHandles.js

var exec = require('child_process').exec;
var querystring = require("querystring");
var fs = require('fs');
var formidable = require("formidable");

function start(response, postData) {
    console.log('request handle "start" is called');
    //非阻塞操作
    /*exec("ls-lah", function(error, stdout, stderr) {
        response.writeHead(200, { 'Content-Type': 'text/plain' });
        response.write(stdout);
        response.end();
    })*/
    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">' +
        '<input type="submit" value="Upload file" />' +
        '</form>' +
        '</body>' +
        '</html>';
    response.writeHead(200, { 'Content-Type': 'text/html' });
    response.write(body);
    response.end();
}

/*function upload(response, postData) {
    console.log('request handle "upload" is called');
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write("You've sent: " + querystring.parse(postData).text);
    response.end();
}*/
function upload(response, request) {
    console.log("Request handler 'upload' was called.");

    var form = new formidable.IncomingForm();
    console.log("about to parse");
    form.parse(request, function(error, fields, files) {
        console.log("parsing done");
        fs.renameSync(files.upload.path, "./tmp/test.jpg");
        response.writeHead(200, { "Content-Type": "text/html" });
        response.write("received image:<br/>");
        response.write("<img src='/show' />");
        response.end();
    });
}

function show(response, postData) {
    console.log('request handle "show" is called');
    fs.readFile('./tmp/test.jpg', "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/jpg" });
            response.write(file, "binary");
            response.end();
        }
    })
}
exports.start = start;
exports.upload = upload;
exports.show = show;

参考文献:https://www.nodebeginner.org/index-zh-cn.html#how-function-passing-makes-our-http-server-work

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35425276/article/details/80349375
个人分类: node
想对作者说点什么? 我来说一句

Node.js从入门到精通_中文高清.pdf

2017年10月26日 9.16MB 下载

Linux运维从入门高级全套案例v3

2017年11月10日 9.62MB 下载

NodeJs从入门到精通(完整版)

2016年09月19日 7.74MB 下载

Dubbo入门到精通架构高级课程

2017年10月24日 49B 下载

Node.js从入门到放弃

Node.js

mua_mua_mua mua_mua_mua

2017-11-28 12:44:44

阅读数:116

dubbo入门到精通视频

2018年01月18日 49B 下载

没有更多推荐了,返回首页

不良信息举报

Node之从入门到高级入门

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭