`
sillycat
  • 浏览: 2542911 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

NODEJS(2)File Upload Sample with routers and handlers

 
阅读更多
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/

分享到:
评论

相关推荐

    nodejs-file-downloader

    nodejs-file-downloader 是一个用于下载文件的简单实用程序。 它隐藏了处理流、重定向、路径和重复文件名的复杂性。 可以自动重复失败的下载。 如果您遇到任何错误或有疑问,请不要犹豫,打开一个问题。安装$ npm ...

    Web Development with MongoDB and NodeJS(2nd) 无水印pdf

    Web Development with MongoDB and NodeJS(2nd) 英文无水印pdf 第2版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,...

    nodejs-file-upload-and-csv-parse

    nodejs文件上传和csv解析该项目部署了Express框架和fast-csv模块,以实现文件上传和cvs文件解析的功能。 测试基于供应商提供的购物清单csv文件,并且我还提供了提交纯购物表单的功能。购物形式在类别下显示税率。 在...

    File-upload-Angular2-Nodejs:使用angular 2和node.js上传文件

    git clone https://github.com/rahil471/File-upload-Angular2-Nodejs.git file-upload 导航到节点应用程序cd file-upload/node-app 安装依赖项npm install 全局npm install gulp -g 启动节点服务器gulp 打开一...

    nodeJs-file-upload:带进度条的 nodeJs 文件上传

    带进度条的 nodeJs 文件上传 带进度条的 nodeJs 中的简单文件上传 使用的技术: NodeJs, expressJs, bootstrap, jquery npm install node app.js 如需演示,请单击此链接

    nodejs ssh2基本功能的封装

    nodejs ssh2基本功能的封装,连接,下载,上传文件,下载文件,上传文件夹,下载文件夹,创建目录,删除目录,运行shell命令

    Learn With Angular 4, Bootstrap, and NodeJS epub

    Learn With Angular 4, Bootstrap, and NodeJS 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    docker-nodejs-app-sample

    使用docker-compose的nodejs todo应用程序从docker-compose up -d开始您可以通过访问127.0.0.1:3000/todos访问该应用程序。在mysql中创建表use sampleDb;CREATE TABLE `todos` ( `id` int(11) NOT NULL AUTO_...

    nodejs oauth 2 例子代码

    nodejs 搭建oauth服务器的代码 Install nodejs and npm and then, simply run npm install and npm start. The server should now be running at http://localhost:3000.

    ec2-nodejs-docker-sample:ec2-nodejs-docker-sample

    通过构建Docker映像在本地进行... -t节点EC2-测试 通过运行该应用程序进行本地测试。 暴露端口3000 (我们稍后将使用Nginx反向代理将HTTPS端口80请求发送到localhost:3000) 泊坞窗运行-p 3000:3000 node-ec2-test

    Web Development with MongoDB and NodeJS(PACKT,2ed,2015)

    Using these two technologies together, web applications can be built quickly and easily and deployed to the cloud with very little difficulty. The book will begin by introducing you to the ...

    nodejs-file-stucture-express:REST API 的 Nodejs Express 项目文件结构

    cd nodejs-file-stucture-express npm install or npm i npm run dev (For Development environment) OR npm run staging (For Staging environment) OR npm run prod (For Production environment) 贡献 欢

    NodeJs form-data格式传输文件的方法

    本文介绍了Node Js 使用KOA处理form-data格式传输过来的文件,分享给大家。...form表单【注意:enctype=”multipart/form-data”】上传文件时,首先会将文件上传到你本机的temp目录,然后执行move_upload_file

    aot-nodejs-feedparser-sample:范例程式码

    aot-nodejs-feedparser-sample 这是示例代码,以及我。 运行项目 在开始之前,请确保已安装NodeJS0.10.x。 在终端上,运行: $ cd FeedparserSample/ $ npm install 跑步: $ node app.js 用法示例 将您的浏览器...

    nodejs2.zip

    nodejs入门到实战(一、二、三)源代码,对应分类:https://blog.csdn.net/zengraoli/category_10327904.html 中的文章 nodejs入门到实战(一)、nodejs入门到实战(二)、nodejs入门到实战(三)

    Vue3 + nodejs 实战 - 文件上传项目 (图片上传,多文件上传,拖拽上传,大文件分片上传,断点续传)后端源码

    这个就是Vue3 + nodejs 实战 --- 文件上传项目的前端源码(Vue3)+ 后端(Nodejs),实现的文件上传的代码,主要实现了(图片上传,多文件上传,拖拽上传,大文件分片上传,断点续传)这些功能,如果对文件上传有...

    aws-nodejs-sample

    在aws-nodejs-sample中,开发者可能使用EC2实例来托管他们的Node.js应用,确保应用能够在全球范围内快速响应请求。 接下来是Amazon Simple Storage Service (S3),它是AWS提供的对象存储服务。在这个示例中,S3可能...

Global site tag (gtag.js) - Google Analytics