Node.js

Node.js

参考 http://nodejs.org/

学习文档:

http://cnodejs.org/api/

http://cnodejs.org/cman/ (中文手册)

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

AN EXAMPLE: WEBSERVER

This simple web server written in Node responds with "Hello World" for every request.

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

To run the server, put the code into a file example.js and execute it with the node program:

% node example.js
Server running at http://127.0.0.1:1337/

Here is an example of a simple TCP server which listens on port 1337 and echoes whatever you send it:

var net = require('net');

var server = net.createServer(function (socket) {
socket.write("Echo server\r\n");
socket.pipe(socket);
});

server.listen(1337, "127.0.0.1");

**** **** 来自 Node.js 究竟是什么? http://www.ibm.com/developerworks/cn/opensource/os-nodejs/ **** ****

示例 Node 应用程序

最后,我们来看一些代码!让我们将讨论过的所有内容汇总起来,从而创建我们的第一个 Node 应用程序。我们已经知道,Node 对于处理高流量应用程序很理想,所以我们将创建一个非常简单的 Web 应用程序,一个为实现最快速度而构建的应用程序。下面是 “老板” 交代的关于我们的样例应用程序的具体要求:创建一个随机数字生成器 RESTful API。这个应用程序应该接受一个输入:一个名为 “number” 的参数。然后,应用程序返回一个介于 0 和该参数之间的随机数字,并将生成的数字返回给调用者。由于 “老板” 希望该应用程序成为一个广泛流行的应用程序,因此它应该能处理 50,000 个并发用户。我们来看看以下代码:

清单 2. Node 随机数字生成器

                
// 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 languages
var 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(80);

// Output a String to the console once the server starts up, letting us know everything
//
starts up correctly
console.log("Random Number Generator Running...");

启动应用程序

将上面的代码放入一个名为 “random.js” 的文件中。现在,要启动这个应用程序并运行它(以便创建 HTTP 服务器并监听端口 80 上的连接),只需在您的命令提示中输入以下命令:% node random.js。下面是服务器已经启动并运行时看起来的样子:

root@ubuntu:/home/moila/ws/mike# node random.js
Random Number Generator Running...

访问应用程序

应用程序已经启动并运行。Node 正在监听所有连接,我们来测试一下。由于我们创建了一个简单的 RESTful API,所以可以使用 Web 浏览器来访问这个应用程序。键入以下地址(确保您已完成了上面的步骤):http://localhost/?number=27。

您的浏览器窗口将更改到一个介于 0 到 27 之间的随机数字。单击浏览器上的 “重新载入” 按钮,您会得到另一个随机数字。就是这样,这就是您的第一个 Node 应用程序!

Node 对什么有好处?

到此为止,您可能能够回答 “Node 是什么” 这个问题了,但您可能还有一个问题:“Node 有什么用途?” 这是一个需要提出的重要问题,因为肯定有些东西能受益于 Node。

它对什么有好处?

正如您此前所看到的,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 的服务器所做的那样,那看起来似乎是一种明智之举。

参考资料

学习

**** **** **** ****


参考文章

http://nodejs.org/

Node.js 究竟是什么?




原文地址:https://www.cnblogs.com/bruceleeliya/p/2304545.html