从IncomingMessage中读取数据而不在Node.js中使用(Hapi.js)

时间:2018-05-09 20:55:52

标签: node.js stream request hapijs

在Node.js服务器中,请求是IncomingMessage的实例。反过来,IncomingMessage实现了Readable Stream接口。

如果我们想输出整个请求体,我们应该实现这样的事情:

req.on('data', chunk => {
   console.log(chunk.toString());
});

但是,这段代码消耗了流中的数据,我需要将数据保留在流中以便以后使用。有没有办法从流中读取数据而不消耗它?

如果没有,是否可以将数据重新排队到流?

就我而言,我正在使用Hapi.js.可以通过request.raw.req访问请求流。我的代码如下所示:

const server = Hapi.server({ port: 3000, host: 'localhost' });

server.route({
    method: 'POST',
    path: '/',
    handler: (request, h) => {
        var req = request.raw.req;    // Get the IncomingMessage

        req.on('data', chunk => {
           console.log(chunk.toString());
        });
        return 'Hello, world!';
    }
});
server.start();

1 个答案:

答案 0 :(得分:1)

Adding the following route options does the trick:

options: {
    payload: {
        output: 'data',
        parse: false
    }
}

This forces Hapijs to read the payload and output it as data, i. e., request.payload will be a Buffer instead of a stream.

The parse option is optional. When set to false, Hapijs will ignore the content-type of the request and will not try to parse it.