- 浏览: 2542833 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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/
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/
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 468NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 330Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 377Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 468NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 414Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 332Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 243GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 445GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 321GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 307Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 286Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 303Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 282NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 257Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 565NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 257Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 362Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 366Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
nodejs-file-downloader 是一个用于下载文件的简单实用程序。 它隐藏了处理流、重定向、路径和重复文件名的复杂性。 可以自动重复失败的下载。 如果您遇到任何错误或有疑问,请不要犹豫,打开一个问题。安装$ npm ...
Web Development with MongoDB and NodeJS(2nd) 英文无水印pdf 第2版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,...
nodejs文件上传和csv解析该项目部署了Express框架和fast-csv模块,以实现文件上传和cvs文件解析的功能。 测试基于供应商提供的购物清单csv文件,并且我还提供了提交纯购物表单的功能。购物形式在类别下显示税率。 在...
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 文件上传 带进度条的 nodeJs 中的简单文件上传 使用的技术: NodeJs, expressJs, bootstrap, jquery npm install node app.js 如需演示,请单击此链接
nodejs ssh2基本功能的封装,连接,下载,上传文件,下载文件,上传文件夹,下载文件夹,创建目录,删除目录,运行shell命令
Learn With Angular 4, Bootstrap, and NodeJS 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
使用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服务器的代码 Install nodejs and npm and then, simply run npm install and npm start. The server should now be running at http://localhost:3000.
通过构建Docker映像在本地进行... -t节点EC2-测试 通过运行该应用程序进行本地测试。 暴露端口3000 (我们稍后将使用Nginx反向代理将HTTPS端口80请求发送到localhost:3000) 泊坞窗运行-p 3000:3000 node-ec2-test
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 ...
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) 贡献 欢
本文介绍了Node Js 使用KOA处理form-data格式传输过来的文件,分享给大家。...form表单【注意:enctype=”multipart/form-data”】上传文件时,首先会将文件上传到你本机的temp目录,然后执行move_upload_file
aot-nodejs-feedparser-sample 这是示例代码,以及我。 运行项目 在开始之前,请确保已安装NodeJS0.10.x。 在终端上,运行: $ cd FeedparserSample/ $ npm install 跑步: $ node app.js 用法示例 将您的浏览器...
nodejs入门到实战(一、二、三)源代码,对应分类:https://blog.csdn.net/zengraoli/category_10327904.html 中的文章 nodejs入门到实战(一)、nodejs入门到实战(二)、nodejs入门到实战(三)
这个就是Vue3 + nodejs 实战 --- 文件上传项目的前端源码(Vue3)+ 后端(Nodejs),实现的文件上传的代码,主要实现了(图片上传,多文件上传,拖拽上传,大文件分片上传,断点续传)这些功能,如果对文件上传有...
在aws-nodejs-sample中,开发者可能使用EC2实例来托管他们的Node.js应用,确保应用能够在全球范围内快速响应请求。 接下来是Amazon Simple Storage Service (S3),它是AWS提供的对象存储服务。在这个示例中,S3可能...