NodeJS 初体验

来源:互联网 发布:淘宝店铺评价好的包包 编辑:程序博客网 时间:2024/06/03 19:30
NodeJS对什么有好处?
Node 非常适合以下情况:在响应客户端之前,您预计可能有很高的流量,但所需的服务器端逻辑和处理不一定很多。Node 表现出众的典型示例包括:
RESTful API
提供 RESTful API 的 Web 服务接收几个参数,解析它们,组合一个响应,并返回一个响应(通常是较少的文本)给用户。这是适合 Node 的理想情况,因为您可以构建它来处理数万条连接。它仍然不需要大量逻辑;它本质上只是从某个数据库中查找一些值并将它们组成一个响应。由于响应是少量文本,入站请求也是少量的文本,因此流量不高,一台机器甚至也可以处理最繁忙的公司的 API 需求。
Twitter 队列
想像一下像 Twitter 这样的公司,它必须接收 tweets 并将其写入数据库。实际上,每秒几乎有数千条 tweet 达到,数据库不可能及时处理高峰时段所需的写入数量。Node 成为这个问题的解决方案的重要一环。如您所见,Node 能处理数万条入站 tweet。它能快速而又轻松地将它们写入一个内存排队机制(例如 memcached),另一个单独进程可以从那里将它们写入数据库。Node 在这里的角色是迅速收集 tweet,并将这个信息传递给另一个负责写入的进程。想象一下另一种设计(常规 PHP 服务器会自己尝试处理对数据库本身的写入):每个 tweet 都会在写入数据库时导致一个短暂的延迟,因为数据库调用正在阻塞通道。由于数据库延迟,一台这样设计的机器每秒可能只能处理 2000 条入站 tweet。每秒处理 100 万条 tweet 则需要 500 个服务器。相反,Node 能处理每个连接而不会阻塞通道,从而能够捕获尽可能多的 tweets。一个能处理 50,000 条 tweet 的 Node 机器仅需 20 台服务器即可。
电子游戏统计数据
如果您在线玩过《使命召唤》这款游戏,当您查看游戏统计数据时,就会立即意识到一个问题:要生成那种级别的统计数据,必须跟踪海量信息。这样,如果有数百万玩家同时在线玩游戏,而且他们处于游戏中的不同位置,那么很快就会生成海量信息。Node 是这种场景的一种很好的解决方案,因为它能采集游戏生成的数据,对数据进行最少的合并,然后对数据进行排队,以便将它们写入数据库。使用整个服务器来跟踪玩家在游戏中发射了多少子弹看起来很愚蠢,如果您使用 Apache 这样的服务器,可能会 有一些有用的限制;但相反,如果您专门使用一个服务器来跟踪一个游戏的所有统计数据,就像使用运行 Node 的服务器所做的那样,那看起来似乎是一种明智之举。


安装完NodeJS后开发部署一个简单的web应用非常迅速。下面我们创建一个随机数字生成器 RESTful API。这个应用程序应该接受一个输入:一个名为 “number” 的参数。然后,应用程序返回一个介于 0 和该参数之间的随机数字,并将生成的数字返回给调用者。由于 “老板” 希望该应用程序成为一个广泛流行的应用程序,因此它应该能处理 50,000 个并发用户。
1. 创建文件random.js并输入以下代码
// these modules need to be imported in order to use them.// Node has several modules.  They are like any #include// or import statement in other languagesvar http = require("http");var url = require("url");// The most important line in any Node file.  This function// does the actual process of creating the server.  Technically,// Node tells the underlying operating system that whenever a// connection is made, this particular callback function should be// executed.  Since we're creating a web service with REST API,// we want an HTTP server, which requires the http variable// we created in the lines above.// Finally, you can see that the callback method receives a 'request'// and 'response' object automatically.  This should be familiar// to any PHP or Java programmer.http.createServer(function(request, response) {     // The response needs to handle all the headers, and the return codes     // These types of things are handled automatically in server programs     // like Apache and Tomcat, but Node requires everything to be done yourself     response.writeHead(200, {"Content-Type": "text/plain"});     // Here is some unique-looking code.  This is how Node retrives     // parameters passed in from client requests.  The url module     // handles all these functions.  The parse function     // deconstructs the URL, and places the query key-values in the     // query object.  We can find the value for the "number" key     // by referencing it directly - the beauty of JavaScript.     var params = url.parse(request.url, true).query;     var input = params.number;     // These are the generic JavaScript methods that will create     // our random number that gets passed back to the caller     var numInput = new Number(input);     var numOutput = new Number(Math.random() * numInput).toFixed(0);          // Write the random number to response     response.write(numOutput);          // Node requires us to explicitly end this connection.  This is because     // Node allows you to keep a connection open and pass data back and forth,     // though that advanced topic isn't discussed in this article.     response.end();   // When we create the server, we have to explicitly connect the HTTP server to   // a port.  Standard HTTP port is 80, so we'll connect it to that one.}).listen(8081);// Output a String to the console once the server starts up, letting us know everything// starts up correctlyconsole.log("Random Number Generator Running...");


2. 在命令行中运行 node random.js
下面是服务器已经启动并运行时看起来的样子:
node random.js
Random Number Generator Running...
引用

你可能会遇到错误代码Error: listen EADDRINUSE
意思是:错误地址使用。‘EADDRINUSE’应该是‘error address in use’的缩写。后来借助google找到了合理的解释,说是你监听的端口已经被使用了!
如过你使用的是Linux,可能会使用如下命令:
sudo fuser -n tcp 80   //查询什么进程占用了80端口
sudo kill pid  *   //kill pid


3. 打开浏览器,输入地址http://localhost:8081/?number=27 你将看到返回的数字结果


参考:
https://github.com/joyent/node/wiki/modules  //可用的模块
https://www.npmjs.org/   NPM是一个Node包管理和分发工具,已经成为了非官方的发布Node模块(包)的标准。