0

我正在开发一个基于 Flatiron Union 的应用程序,似乎我在运行路由之前正在开发日志的简单记录器,所以它不能准确地报告发生了什么。我从 Union 示例中获取了记录器示例代码。这是一个精简的代码示例:

 var
   union = require('union')
   , server;

 server = union.createServer({
   before: [ function (req,res) {
     console.log('before');
     res.writeHead(404, {"Content-Type": "text/plain"});
     res.end("Hello World");
   } ],
   after: [
     function LoggerStream() {
         var stream   = new union.ResponseStream();
         stream.once("pipe", function (req) {
           console.log({res: this.res.statusCode, method: this.req.method});
         });
         return stream;
     }
   ]
 });

 server.listen(8800);
 console.log('union running on 8800');

这是我的控制台中显示的内容:

 $ DEBUG=*  node ./union.js
 union running on 8800
 { res: 200, method: 'GET' }
 before

请注意,当 http 服务器实际返回 404 时,报告的状态为 200。

为什么会出现这种情况?

4

1 回答 1

1

这是我们的邮件列表中indexzero对您问题的最新回复:

斯图尔特,

这实际上是预期的行为。管道链由 union.RoutingStream 实例从以下位置构造:

union.ResponseStream() --> after0 --> after1 --> after2 --> ... --> aftern --> http.Response() (见 https://github.com/flatiron/union/blob /master/lib/routing-stream.js#L74-83 )

因此,pipeafter 链中每个 Stream 上的事件都会立即被调用,但是这些 Stream 中的每个人都有机会通过实现自己的 .pipe() 方法来修改发送到响应的数据。

因此,例如,如果您的 LoggingStream 是

var stream = new union.ResponseStream(); stream.once("数据", function (req) { console.log({res: this.res.statusCode, method: this.req.method}); }); 返回流;

您会看到 console.log 语句按您期望的顺序触发。阅读 Max Ogden 最近关于 Node.js 中的 Streams 及其工作原理的博客文章可能会很有用:http: //maxogden.com/node-streams

干杯,查理

如果您有更多问题,可以在 github、irc(freenode 上的#nodejitsu)和我们的邮件列表 flatironjs@googlegroups.com 上找到我们。:)

于 2012-05-01T04:13:00.323 回答