设为首页 收藏本站
查看: 748|回复: 0

[经验分享] NODEJS(2)File Upload Sample with routers and handlers

[复制链接]

尚未签到

发表于 2017-2-22 09:14:10 | 显示全部楼层 |阅读模式
NODEJS(2)File Upload Sample with routers and handlers

What's needed to "route" requests?
We need to be able to feed the requested URL and possible additional GET and POST parameters into our router, and based on these the router then needs to be able to decide which code to execute(a collection of request handlers that do the actual work when a request is received).

We need other modules in Node.js namely url and querystring.

url module provide methods which extract the URL, and querystring module for query string.

We do some changes in server.js as follow, we can get the requestpath in our URL.
var url = require("url");
...snip...
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
We get these messages on console then:
Request for / received.
Request for /luohua received.
Request for /order.do received.

We create a router.js with these content:
function route(pathname){
            console.log("About to route a request for " + pathname);   
}

exports.route = route;

Pass the function method name to our route and start, refactor server.js as follow:
function start(routeMethod) {
...snip...
routeMethod(pathname);
...snip...

index.js will be changed as follow:
var server = require("./server");
var router = require("./router");

server.start(router.route);

Execution in the kingdom of verbs
Routing to real request handlers
Create a module requestHandlers.js as follow:
function start(){
            console.log("Request handler 'start' was called.");   
}

function upload(){
            console.log("Request handler 'upload' was called.");
}

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

In JavaScript, objects are just collections of name/value pairs, think of a JavaScript object as a dictionary with string keys.
We use a key/value pair, put the functions in value, and pass this map to our router.
index.js
var requestHandlers = require("./requestHandlers");

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

server.start(router.route, handle);

server.js
function start(routeMethod, handleMap) {
...snip...
routeMethod(handleMap,pathname);
...snip...

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

Making the request handlers respond
How to not do it
We will write back the content in response
requestHandlers.js
function start(){
            console.log("Request handler 'start' was called.");   
            return "Hello Start";
}

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

router.js
            if(typeof handleMap[pathname] === 'function'){
                        return handleMap[pathname]();   
            } else {
                        console.log("No request handler found for " + pathname);
                        return "404 Not found";
            }

server.js
response.writeHead(200, {"Content-Type": "text/plain"});
    var content = routeMethod(handleMap,pathname);
    response.write(content);
...snip..

Blocking and non-blocking
We will try to make blocking in request handler, make it wait 10 seconds before returning its "Hello Start" string.

I download the mac version here, Node was installed at /usr/local/bin/node, npm was installed at /usr/local/bin/npm.

And I change the requestHanders.js as follow:
function start(){
  …snip…
  function sleep(milliSeconds){
    var startTime = new Date().getTime();
    while (new Date().getTime() < startTime + milliSeconds);
  }
  
  sleep(10000);
  return "Hello Start";
}

From the code, we can understand that start will take 10 seconds to sleep. But upload will response immediately.
But we hit the URL http://localhost:8888/start first, and then in another tab, hit the URL http://localhost:8888/upload. But both of the URLs are waiting for 10 seconds.

In fact, Node.js is single-threaded. So we will try to do it no-blocking ways. This way we are saying " probablyExpensiveFunction(), please do your stuff, but the single Node.js thread will not wait right here until you are finished, I will continue to execute the lines of code below you. So would you please take this callbackFunction() here and call it when you are finished doing your expensive stuff.

non-blocking exec module
var exec = require("child_process").exec;

function start() {
  console.log("Request handler 'start' was called.");
  var content = "empty";

  exec("ls -lah", function(error, stdout, stderr) {
    content = stdout;
  });
  return content;
}

But this can only show the empty on the page. Because exec really is non-blocking.

Responding request handlers with non-blocking operations
pass the response to route handler in server.js
…snip…
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    route(handle, pathname, response);   
}
…snip...

router.js will handle the response and pass the response to requestHanders.
…snip…
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();
  }
}
…snip…

Handle the response in requestHandlers.js

exec("ls -lah", function(error, stdout, stderr) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(stdout);
    response.end();
});
…snip…
function upload(response) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello Upload");
  response.end();
}

This time everything works fine and we can see the file list under that directory.

references:
http://www.nodebeginner.org/

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-345487-1-1.html 上篇帖子: nodejs v8 实现 ECMA 5 Mozilla 的一些特性 下篇帖子: nodejs对mongodb数据库的增删改查操作
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表