Connect介绍(Just Connect it Already)
发布于 4年前 作者 lenzhang 2614 次浏览 最后一次编辑是 3年前

Connect介绍(Just Connect it Already)


原文链接


                             Translated by lenzhang(zwj8727[@gmail](/user/gmail).com)


Reviewed by goddyzhao(goddy128[@gmail](/user/gmail).com)


感谢社区志愿者们在翻译过程中所提供的帮助


Now that the core APIs of node are really starting to stabilize, I'm moving my attention to helping stabilize the framework scene. One of the things I found really neat from Ruby was the Rack server interface. It allowed any server that followed the spec to host any app that followed the spec. Also (and this is the important part for node) is allowed for generic middleware libraries to do common tasks and functions in a very aspect oriented manner.


现在node的核心api已逐渐稳定,我开始着手提高框架的稳定性。我发现Ruby的Rack server interface很整洁。允许任何遵循规范的服务器主机可以方便的部署任何符合规范的应用程序。同时(这也是node很重的一部分)也允许中间件库以面向切面的方式来完成通用的任务和功能。


My employer, Sencha, has sponsored TJ Holowaychuk and I to write a middleware system for node called Connect in an effort to foster common development in the node community.


UPDATE This article has been updated to use the new connect middleware API.


我的雇主, Sencha, 资助 TJ Holowaychuk和我给node写一个中间件系统,名为: Connect ,目的是以此来推动node社区更快的发展。


UPDATE 这篇文章已经更新为使用新版的connect
middleware api。


So What's New?


有何不同? 


Actually there isn't a lot new here. But then again, there was nothing new about node either. Node uses non-blocking IO for fast scalable servers. That's been known about for years among the C community. It uses event based, single thread javascript for logic. That's exactly what the browser has. Add these together and we all see the huge splash it's made. It's the unique combination of some simple but complimentary ideas that really make these projects zing.


实际上并没有什么新的东西。但话又说回来,node本身也没有什么新的东西。Node使用非阻塞io实现快速可伸缩服务。这种方式在c社区早已被人熟知好几年了。它同时使用基于事件的单线程javascript来实现逻辑。


这正是浏览器的特性。而它将这些组合起来就立刻受到了欢迎和追捧。也正是对这些简单而又值得称赞的创意的独特组合使这个项目火起来了。


Connect tries to abstract and repackage node as little as possible. As a result, the API is fairly node specific, but there aren't a lot of leaky abstractions dripping all over the place. It's fairly solid considering the short time it's been in development so far. Connect adds one new unique aspect to node's HTTP server and that's the idea of layers.


Connect 尝试尽可能小的抽象并重新封装node。最终,其API和node一致,但是提高了抽象层的质量。到目前为止,就从这段短暂的开发期来看,Connect还是相当高质量的。Connect 为node的HTTP服务端添加了一个独特的切面。这也是Connect的精华所在。


 The Integration Problem


整合的问题


 In a normal node HTTP server you usually see code like this.


在node HTTP服务器中,代码通常如下所示:


node-http.js



var http = require('http');

// 开启一个HTTP服务器
http.createServer(function(request, response) {
// 对每个请求都响应“Hello Connect”文本
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello Connect");
}).listen(8081);

And all requests will be served:


所有的请求都将返回如下结果:


HTTP/1.1 200 OK
Content-Type: text/plain
Connection: close
Transfer-Encoding: Identity


Hello Connect

This works great for when you want fast synthetic benchmarks or always want to return the same response for every HTTP request. In most apps, however, this isn't the case. You want some form of request routing. Also you'll want nice enhancements like response body gzipping, smart caching, request logging, pretty error handlers, etc...


上述例子,满足快速测试或者总要求服务器对每个HTTP请求返回同样的结果,这样的需求。但是在大多数程序中并不是这样的情况。你需要某种形式的路由。同时你还需要很好的增强的功能,比如返回内容的gzip压缩,自动缓存,请求日志,漂亮的错误处理等等。


Implementing all these things over and over for each project is a royal pain since they are somewhat non-trivial and usually a project in and of themselves. So ideally the node community has a collection of modules that we can use in common to solve these common tasks. The only roblem is that there is no accepted spec to follow. All these libraries have their own style and way to integrate. This is great for innovation, terrible for someone trying to just get work done and quickly.


一遍又一遍的在每个项目中都实现它们实在是太痛苦了,而这些功能在某种意义上又是不可或缺的并且都是每个项目中的一部分。所以理想的是node社区收集这些常用的模块来解决常见的问题。唯一的问题是需要一个规范来约束。我们常见的其他语言的库都有他们自己的风格和方式来整理。这将促进创作,遏制随意的行为。


Layers to the Rescue


层的出现解决了问题(原文为:层的拯救)


So taking the ideas from Rack and ejsgi, we introduce the idea of layers to the code handling the HTTP request and response. An app is structured like an onion. Every request enters the onion at the outside and traverses layer by layer till it hits something that handles it and generates a response. In Connect terms, these are called filters and providers. Once a layer provides a response, the path happens in reverse.



通过借鉴Rack和ejsgi,我们提出分层来处理http请求和响应的想法。一个程序就像一个洋葱,每一个请求逐层进入洋葱直到遇到一层处理它,并且返回一个响应。在Connect的术语中,我们叫这个filters和providers。一旦某一层提供了response,将直接返回结果。


The Connect framework simply takes the initial request and response objects that come from node's http callback and pass them layer by layer to the configured middleware modules in an application.


在程序中Connect框架简单的将node的http回调函数中的request和response一层又一层的传递给所配置的中间模块。


The example from above, converted to a Connect app looks as follows:


上面的例子转换为connect程序看起来像下面这样。


connect-http.js



var Connect = require('connect');

Connect.createServer(function (req, res, next) {
// 每个请求都响应"Hello Connect"文本.
res.simpleBody(200, "Hello Connect");
}).listen(8080);

And request will output this:


所有的请求都将返回如下结果。


HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 13
Connection: close


Hello Connect

Walkthrough Writing Layers and an Application


尝试编写层和程序


Let's go through a simple app from the top down. It will serve JavaScript files from a folder, cache the result in ram, and log the request and responses. We'll implement our middleware layers from scratch to understand how they work. There are better versions of these built-in.


让我们尝试从头到尾完整地编写一个简单的程序。程序处理文件夹中的JavaScript文件,将结果缓存在内存中,并以日志形式记录请求和返回情况。我们将实现我们的中间件来理解它是如何工作的。。不过,这只是作为例子而已,并不是最好的实现方式。


app.js



var Connect = require('connect');

module.exports = Connect.createServer(
require('./log-it')(),
require('./serve-js')()
);

 

An app is just a call
to Connect.createServer with several handlers in a row.


上述程序只是简单调用了Connect.createServer,同时传递了一些处理程序。


All Connect layers are simply node modules that export a setup function that returns a handle function. The setup function is called at server startup and you can pass in configuration
parameters to it. Then on each request, you have the option at this point to either: A) Serve a response using the res parameter. or B) Pass on control to the next layer in the chain using the next parameter.Since you have raw access to the node request and response objects and the full JavaScript language, the possibilities are endless.


所有的Connect层只是简单的node模块,声明了一个起始函数,这个函数返回一个处理程序。这个起始函数在server启动的时候被调用。你可以传递配置参数到函数里。然后在每次请求的时候,你都可以做如下操作:A)使用res返回一个请求结果。B):使用next参数跳到下一层。因为可以直接访问node request和response对象和整个javascript语言,所以将有无限的可能。


Serve Some Files


提供一些文件服务


Most apps will want to serve some static resources, so let's write a middleware that serves javascript files based on the request url.


大多数的程序都想要提供一些静态文件服务,所以我们一起写一个基于request.url的中间件来提供javascript文件服务。


serve-js.js



var fs = require('fs');


module.exports = function serveJsSetup() {
return function serveJsHandle(req, res, next) {
// 处理所有相对此进程的文件
// 要注意的是,这里为了代码简单,并没有考虑太多的安全问题
fs.readFile(req.url.substr(1), function (err, data) {
if (err) {
next(err);
return;
}
res.simpleBody(200, data, "application/javascript");
});
};
};

Here we are using the built-in node library 'fs' to read the requested file from the hard-drive. Then we're using the Connect provided helper simpleBody on the http response object. Nothing fancy or complicated here.


这里我们使用内置的node库‘fs’来读取所请求的文件。接着我们使用Connect提供的http response对象的simpleBody方法。这一点也不晦涩难懂。


Log It


记录日志


Whenever there is a problem with a server, it's really great to have a log-file somewhere to trace what went wrong. This log module will output a line when a request comes in through the layer, and then another on the way back out.


当服务器有问题的时候,能够有日志文件来跟踪问题发生的原因真是太好了。当请求过来的时候日志模块将会输出一行request日志,和一条返回日志。


log-it.js



module.exports = function logItSetup() {


// 初始化计时器
var counter = 0;

return function logItHandle(req, res, next) {
var writeHead = res.writeHead; // 存储初始函数
counter++;

// 日执行时记录请求
console.log("Request " + counter + " " + req.method + " " + req.url);

// 封装writeHead函数,将其注入到层的出口路径中
res.writeHead = function (code, headers) {
res.writeHead = writeHead; // Put the original back

// 以日志形式记录响应
console.log("Response " + counter + " " + code + " "
+ JSON.stringify(headers));

res.writeHead(code, headers); // 调用初始函数
};

// 传递给下一层
next();
};
};

The setup function is a great place to setup variables used by the middleware across requests. In this case we're initializing the counter for the logger.


在起始函数中初始化跨请求的变量是很方便的。因此为logger初始化了计数器。


In the handler we are using a wrapping idiom to hook into the call to writeHead. In JavaScript functions are values just like anything else. So a great way to wrap functions is to store a reference to the original implementation in a closure variable. Replace the function with a new one, and in the first line of the new function, put the old function definition back. Then on the last line of the replacement function call the original. This is a simple and efficient way to hook into existing object methods since they just look for properties by name and not references to actual function objects.


在处理程序中,我们使用了一种包装句式来挂接到writeHead。在Javascript中函数也是值就像其他的数据类型一样。所以比较好的办法是将函数的引用存储在变量中来构造一个闭包变量。然后使用新函数函数来替换这个,在新函数的第一行将原函数的定义放回来。在新函数的最后一行调用原函数。由于javascript通过属性名而不是引用来标识真正的函数,所以这是将函数挂接到已有对象非常有效的办法。


The standalone console.log call will be called at the beginning of each request cycle, and the nested console.log will be called on the way out by means of the nested writeHead function.


独立的console.log将会在每个请求周期中被调用。嵌套的console.log将会在writeHeader每次被调用的时候调用。


Built-in Middleware


内建中间件


Connect comes with several built-in middleware layers for easy use. A much more robust version of this example could be written using the built-in modules.


Connect内建了很多易用的中间件。我们之前的例子可以使用这些组件构建一个更强大的程序。


app2.js



var Connect = require('connect');


module.exports = Connect.createServer(
Connect.logger(), //以终端通用日志格式记录响应
Connect.responseTime(), //添加一个包含时间信息的特殊头信息
Connect.conditionalGet(), // 为了节省带宽,添加HTTP 304响应头
Connect.cache(), // 为了提高性能,添加一个临时内存缓存
Connect.gzip(), // 有需要的时候,对输出流进行Gzip压缩
Connect.staticProvider(__dirname) // 处理当前目录下所有的静态文件
);

This has proper error-handling, proper HTTP headers, and all sorts of other bells and whistles that are required from a production web server.


上面的程序有很好的错误处理,很好的HTTP头,和其他各种各样的生产环境下的web服务器所需要的组件。


Future and Goals of Connect


Connect愿景


Connect is currently in alpha state. We're looking for community feedback and hope to stabilize into a beta in the next week or so.


Connect当前仍然处在alpha状态。我们在寻找社区的反馈,希望在未来一周或者差不多的时间可以使之进入beta版。


Also what's really needed is for some real frameworks and apps to be written using Connect as a base. TJ is using it internally for a project at work and I plan to convert wheat (The engine to this blog) to use it.


当然我们仍然需要一些真正基于Connect的框架和程序。TJ是一个基于Connect的项目,我打算将wheat(本blog的引擎)替换成TJ。


The true goal of Connect is to help the node community work better together. Connect is the combined effort of some JavaScripters from the node community who want a base system to build world-class web frameworks from.


Connect的真正目的是帮助node社区能够更好的协作。Connect是一些来自node社区JavaScript编程者共同努力地结果,他们想要一个基础的系统来构建出世界级的web框架


There has been a lot of discussion on the topic of middleware and now is the time to write some code, use it, and do it. The popularity of JavaScript itself is proof that what really succeeds is real-world implementations, not substance-less discussions on the very best way to do something. Like node, our goal is to make something simple, but correct, and let others build from there.


我们已经花了很多篇幅讨论中间件,现在是时间写一些代码里,使用它,并行动。javascript的流行证明真正的成功是去实现,而不是毫无实质的讨论。就像node,我们的目标是做一些简单但是正确事情,使其他人基于此构建。


What you Should Do


你应该做什么


Connect is cool, I gave two presentations on it in the past week at txjs and swdc and people loved it. TJ and I have done all we can for now and need some community feedback in order to move on. If you are interested in node and want to help shape the future of web frameworks please do the following:


Connect是很酷的,我上周在txjs和swdc做了两次演讲,大家都很喜欢他。TJ和我已经做了我们目前为止能做的所有事情,我们需要得到一些社区的反馈才可能够继续走下去。如果你对node感兴趣并且希望能够帮助塑造web框架的未来,请做以下的事情:




  • Install node
    if you haven't already. (I suggest using ivy)   如果你还没有安装node,请安装

  • Clone Connect.  获取一份Connect的代码

  • Go through the examples in the code-base. (The app.js file is launched with  the connect executable) 运行code-base里的例子

  • Write your own code using Connect. (Or port your favorite node framework)  使用Connect编写你自己的代码,或者请提交你最喜欢的node框架代码

  • Send feedback  through github and the normal node community channels. (irc and mailing list)  通过github反馈或者其他社区途径(irc或者邮件列表)

  • Tweet about it to spread the word. (This only works if everyone uses it)在tweet上发与之相关的推文来宣告全世界(只有全世界都用tweet才可以)


Deploying Connect Apps


开发Connect程序


See the deploying-node-with-spark article for tips on how to set up a production server using Connect and Spark.


阅读deploying-node-with-spark文章来获取一些有关如何建立生产环境的信息。


 
3 回复

哇, 很酷. 有了它nodejs提高了一层境界

了解connect对于了解express有很大的意义的

很有意义的一篇文章,普及了一下知识,对我这个新手很有用

回到顶部