Node.js学习笔记【1】入门(服务器JS、函数式编程、阻塞与非阻塞、回调、事件、内部和外部模块)

JavaScript与Node.js

 

Node.js事实上既是一个运行时环境,同时又是一个库。

 

使用Node.js时,我们不仅仅在实现一个应用,同时还实现了整个HTTP服务器。

 

一个基础的HTTP服务器

 

server.js:一个可以工作的HTTP服务器

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2.   
  3. http.createServer(function(request, response) {  
  4.     response.writeHead(200, {"Content-Type""text/plain"});  
  5.     response.write("Hello World");  
  6.     response.end();  
  7. }).listen(8888);  

进行函数传递

 

同样的效果:

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2.   
  3. function onRequest(request, response) {  
  4.     response.writeHead(200, {"Content-Type""text/plain"});  
  5.     response.write("Hello World");  
  6.     response.end();  
  7. }  
  8.   
  9. http.createServer(onRequest).listen(8888);  

基于事件驱动的回调

 

我们创建了一个服务器,并且向创建它的方法传递了一个函数。无论何时我们的服务器收到一个请求,这个函数就会被调用。

 

服务器是如何处理请求的

 

当收到请求时,使用response.writeHead()函数发送一个HTTP状态200和HTTP头的内容类型(content-type),使用response.write()函数在HTTP相应主体中发送文本“Hello World”。最后,我们调用 response.end() 完成响应。

 

服务器端的模块放在哪里

 

把某段代码变成模块意味着我们需要把我们希望提供其功能的部分导出到请求这个模块的脚本。

 

代码修改如下:

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2.   
  3. function start() {  
  4.     function onRequest(request, response) {  
  5.         console.log("Request received.");  
  6.         response.writeHead(200, {"Content-Type""text/plain"});  
  7.         response.write("Hello World");  
  8.         response.end();  
  9.     }  
  10.     http.createServer(onRequest).listen(8888);  
  11.     console.log("Server has started.");  
  12. }  
  13.   
  14. exports.start = start;  

index.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var server = require("./server");  
  2.   
  3. server.start();  

如何来进行请求的“路由”

 

处理不同的HTTP请求,叫做“路由选择”。

 

【图】url-query

 


onRequest()函数加上一些逻辑,用来找到浏览器请求的URL路径。

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2. var url = require("url");  
  3.   
  4. function start() {  
  5.     function onRequest(request, response) {  
  6.         var pathname = url.parse(request.url).pathname;  
  7.         console.log("Request for " + pathname + " received.");  
  8.         response.writeHead(200, {"Content-Type""text/plain"});  
  9.         response.write("Hello World ");  
  10.         response.end();  
  11.     }  
  12.     http.createServer(onRequest).listen(8888);  
  13.     console.log("Server has started.");  
  14. }  
  15.   
  16. exports.start = start;  

router.js:路由

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function route(pathname) {  
  2.     console.log("About to route a request for " + pathname);  
  3. }  
  4.   
  5. exports.route = route;  

扩展一下服务器的start()函数,以便将路由函数作为参数传递过去。

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2. var url = require("url");  
  3.   
  4. function start(route) {  
  5.     function onRequest(request, response) {  
  6.         var pathname = url.parse(request.url).pathname;  
  7.         console.log("Request for " + pathname + " received.");  
  8.   
  9.         route(pathname);  
  10.           
  11.         response.writeHead(200, {"Content-Type""text/plain"});  
  12.         response.write("Hello World ");  
  13.         response.end();  
  14.     }  
  15.     http.createServer(onRequest).listen(8888);  
  16.     console.log("Server has started.");  
  17. }  
  18.   
  19. exports.start = start;  

修改index.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var server = require("./server");  
  2. var router = require("./router");  
  3.   
  4. server.start(router.route);  

路由给真正的请求处理程序

 

requestHandlers.js:请求处理程序

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function start(response) {  
  2.     console.log("Request handler 'start' was called.");  
  3. }  
  4.   
  5. function upload(response, request) {  
  6.     console.log("Request handler 'upload' was called.");  
  7. }  
  8.   
  9. exports.start = start;  
  10. exports.upload = upload;  

确定将一系列请求处理程序通过一个对象来传递,并且需要使用松耦合的方式将这个对象注入到route()函数中。

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var server = require("./server");  
  2. var router = require("./router");  
  3. var requestHandlers = require("./requestHandlers");  
  4.   
  5. var handle = {};  
  6. handle["/"] = requestHandlers.start;  
  7. handle["/start"] = requestHandlers.start;  
  8. handle["/upload"] = requestHandlers.upload;  
  9.   
  10. server.start(router.route, handle);  

完成对象的定义之后,我们把它作为额外的参数传递给服务器,为此将server.js修改如下:

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2. var url = require("url");  
  3.   
  4. function start(route, handle) {  
  5.     function onRequest(request, response) {  
  6.         var pathname = url.parse(request.url).pathname;  
  7.         console.log("Request for " + pathname + " received.");  
  8.   
  9.         route(handle, pathname);  
  10.   
  11.         response.writeHead(200, {"Content-Type""text/plain"});  
  12.         response.write("Hello World");  
  13.         response.end();  
  14.     }  
  15.     http.createServer(onRequest).listen(8888);  
  16.     console.log("Server has started.");  
  17. }  
  18.   
  19. exports.start = start;  

在router.js文件中修改route函数。

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function route(handle, pathname) {  
  2.     console.log("About to route a request for " + pathname);  
  3.     if(typeof handle[pathname] === 'function') {  
  4.         handle[pathname]();  
  5.     } else {  
  6.         console.log("No request handler found for " + pathname);  
  7.     }  
  8. }  
  9.   
  10. exports.route = route;  

让请求处理程序作出响应


不好的是实现方式(阻塞)

 

requesHandler.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function start(response) {  
  2.     console.log("Request handler 'start' was called.");  
  3.   
  4.     function sleep(milliSeconds) {  
  5.         var startTime = new Date().getTime();  
  6.         while (new Date().getTime() < startTime + milliSeconds);  
  7.     }  
  8.   
  9.     sleep(10000);  
  10.     return "Hello Start";  
  11. }  
  12.   
  13. function upload(response, request) {  
  14.     console.log("Request handler 'upload' was called.");  
  15.     return "Hello Upload";  
  16. }  
  17.   
  18. exports.start = start;  
  19. exports.upload = upload;  

router.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function route(handle, pathname) {  
  2.     console.log("About to route a request for " + pathname);  
  3.     if(typeof handle[pathname] === 'function') {  
  4.         return handle[pathname]();  
  5.     } else {  
  6.         console.log("No request handler found for " + pathname);  
  7.         return "404 Not found";  
  8.     }  
  9. }  
  10.   
  11. exports.route = route;  

server.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2. var url = require("url");  
  3.   
  4. function start(route, handle) {  
  5.     function onRequest(request, response) {  
  6.         var pathname = url.parse(request.url).pathname;  
  7.         console.log("Request for " + pathname + " received.");  
  8.   
  9.         response.writeHead(200, {"Content-Type""text/plain"});  
  10.         var content = route(handle, pathname);  
  11.         response.write(content);  
  12.         response.end();  
  13.     }  
  14.     http.createServer(onRequest).listen(8888);  
  15.     console.log("Server has started.");  
  16. }  
  17.   
  18. exports.start = start;  

阻塞与非阻塞

 

要用非阻塞操作,我们需要使用回调,通过将函数作为参数传递给其他需要花时间做处理的函数。

 

对Node.js来说,它是这样处理的:“嘿,probablyExpensiveFunction() 【这里指的就是需要花时间处理的函数】,你继续处理你的事情,我(Node.js线程)先不等你了,我继续去处理你后面的代码,请你提供一个callbackFunction(),等你处理完之后,我会去调用该回调函数的。”

 

以非阻塞操作进行请求响应

 

到目前为止,我们的应用已经可以通过应用各层之间传递值的方式(请求处理程序–> 请求路由 -> 服务器)将请求处理程序返回的内容(请求处理程序最终要显示给用户的内容)传递给HTTP服务器。

 

现在我们采用如下这种新的是实现方式:相对采用将内容传递给服务器的方式,我们这次采用将服务器“传递”给内容的方式。从实践角度来说,就是将response对象(从服务器的回调函数onRequest()获取)通过请求路由传递给请求处理程序。随后,处理程序就可以采用该对象上的函数来对请求作出响应。

 

server.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2. var url = require("url");  
  3.   
  4. function start(route, handle) {  
  5.     function onRequest(request, response) {  
  6.         var pathname = url.parse(request.url).pathname;  
  7.         console.log("Request for " + pathname + " received.");  
  8.   
  9.         route(handle, pathname, response);  
  10.     }   
  11.   
  12.     http.createServer(onRequest).listen(8888);  
  13.     console.log("Server has started.");  
  14. }  
  15.   
  16. exports.start = start;  

router.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function route(handle, pathname, response) {  
  2.     console.log("About to route a request for " + pathname);  
  3.     if(typeof handle[pathname] === 'function') {  
  4.         handle[pathname](response);  
  5.     } else {  
  6.         console.log("No request handler found for " + pathname);  
  7.         response.writeHead(404, {"Content-type""text/plain"});  
  8.         response.write("404 Not found");  
  9.         response.end();  
  10.     }  
  11. }  
  12.   
  13. exports.route = route;  

requestHandler.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var exec = require("child_process").exec;  
  2.   
  3. function start(response) {  
  4.     console.log("Request handler 'start' was called.");  
  5.     var content = "empty";  
  6.   
  7.     exec("dir"function (error, stdout, stderr) {  
  8.         response.writeHead(200, {"Content-type""text/plain"});  
  9.         response.write(stdout);  
  10.         response.end();  
  11.     });  
  12. }  
  13.   
  14. function upload(response) {  
  15.     console.log("Request handler 'upload' was called.");  
  16.     response.writeHead(200, {"Content-type""text/plain"});  
  17.     response.write("Hello Upload");  
  18.     response.end();  
  19. }  
  20.   
  21. exports.start = start;  
  22. exports.upload = upload;  

更加有用的场景

 

首先,让我们来看看如何处理POST请求(非文件上传),之后,我们使用Node.js的一个用于文件上传的外部模块。

 

处理POST请求

 

我们显示一个文本区(textarea)供用户输入内容,然后通过POST请求提交给服务器。最后,服务器接受到请求,通过处理程序将输入的内容展示到浏览器中。

 

/start请求处理程序用于生成带文本区的表单,因此,我们将requestHandlers.js修改为如下形式:

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var exec = require("child_process").exec;  
  2.   
  3. function start(response) {  
  4.     console.log("Request handler 'start' was called.");  
  5.   
  6.     var body = '<html>'+  
  7.         '<head>'+  
  8.         '<meta http-equiv="Content-Type" content="text/html; '+  
  9.         'charset=UTF-8" />'+  
  10.         '</head>'+  
  11.         '<body>'+  
  12.         '<form action="/upload" method="post">'+  
  13.         '<textarea name="text" rows="20" cols="60"></textarea>'+  
  14.         '<input type="submit" value="Submit text" />'+  
  15.         '</form>'+  
  16.         '</body>'+  
  17.         '</html>';  
  18.   
  19.     response.writeHead(200, {"Content-Type""text/html"});  
  20.     response.write(body);  
  21.     response.end();  
  22. }  
  23.   
  24. function upload(response) {  
  25.     console.log("Request handler 'upload' was called.");  
  26.     response.writeHead(200, {"Content-type""text/plain"});  
  27.     response.write("Hello Upload");  
  28.     response.end();  
  29. }  
  30.   
  31. exports.start = start;  
  32. exports.upload = upload;  

为了使整个过程非阻塞,Node.js会将POST数据拆分成很多小的数据块,然后通过触发特定的事件,将这些小数据块传递给回调函数。这里的特定的事件有data事件(表示新的小数据块到达了)以及end事件(表示所有的数据都已经接受完毕)。

 

回调函数通过在request对象上注册监听器来实现。这里的request对象是每次接收到HTTP请求时候,都会把该对象传递给onRequest回调函数。

 

server.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var http = require("http");  
  2. var url = require("url");  
  3.   
  4. function start(route, handle) {  
  5.     function onRequest(request, response) {  
  6.         var postData = "";  
  7.         var pathname = url.parse(request.url).pathname;  
  8.         console.log("Request for " + pathname + " received.");  
  9.   
  10.         request.setEncoding("utf-8");  
  11.   
  12.         request.addListener("data"function(postDataChunk) {  
  13.         postData += postDataChunk;  
  14.         console.log("Reveived POST data chunk '" +   
  15.         postDataChunk + "'.");  
  16.     });  
  17.   
  18.     request.addListener("end"function() {  
  19.         route(handle, pathname, response, postData);  
  20.     })  
  21.     }  
  22.     http.createServer(onRequest).listen(8888);  
  23.     console.log("Server has started.");  
  24. }  
  25.   
  26. exports.start = start;  

router.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. function route(handle, pathname, response, postData) {  
  2.     console.log("About to route a request for " + pathname);  
  3.     if(typeof handle[pathname] === 'function') {  
  4.         handle[pathname](response, postData);  
  5.     } else {  
  6.         console.log("No request handler found for " + pathname);  
  7.         response.writeHead(404, {"Content-type""text/plain"});  
  8.         response.write("404 Not found");  
  9.         response.end();  
  10.     }  
  11. }  
  12.   
  13. exports.route = route;  

requestHandlers.js(使用querystring模块获取text字段)

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var querystring = require("querystring");  
  2.   
  3. function start(response, postData) {  
  4.     console.log("Request handler 'start' was called.");  
  5.   
  6.     var body = '<html>'+  
  7.         '<head>'+  
  8.         '<meta http-equiv="Content-Type" content="text/html; '+  
  9.         'charset=UTF-8" />'+  
  10.         '</head>'+  
  11.         '<body>'+  
  12.         '<form action="/upload" method="post">'+  
  13.         '<textarea name="text" rows="20" cols="60"></textarea>'+  
  14.         '<input type="submit" value="Submit text" />'+  
  15.         '</form>'+  
  16.         '</body>'+  
  17.         '</html>';  
  18.   
  19.     response.writeHead(200, {"Content-Type""text/html"});  
  20.     response.write(body);  
  21.     response.end();  
  22. }  
  23.   
  24. function upload(response, postData) {  
  25.     console.log("Request handler 'upload' was called.");  
  26.     response.writeHead(200, {"Content-type""text/plain"});  
  27.     response.write("You've sent: " + querystring.parse(postData).text);  
  28.     response.end();  
  29. }  
  30.   
  31. exports.start = start;  
  32. exports.upload = upload;  

处理文件上传

 

允许用户上传图片,并将该图片在浏览器中显示出来。

 

需要将该文件读取到我们的服务器中,使用一个叫fs的模块。

 

完整的代码在Github:https://github.com/manuelkiessling/NodeBeginnerBook/tree/master/code/application

 

总结

 

介绍了:服务器JavaScript、函数式编程、阻塞与非阻塞、回调、事件、内部和外部模块等等。

 

当然了,还有许多没有介绍到的:如何操作数据库、如何进行单元测试、如何开发Node.js的外部模块以及一些简单的诸如如何获取GET请求之类的方法。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值