Reputation: 1410
In a Node.js server, the requests are instances of IncomingMessage. In turn, IncomingMessage
implements the Readable Stream interface.
If we want to output the whole request body, we should implement something like this:
req.on('data', chunk => {
console.log(chunk.toString());
});
But, this piece of code consumes the data in the stream and I need the data to remain in the stream to be consumed later. Is there any way to read the data from the stream without consuming it?
If not, is it possible to re-queue the data to stream?
In my case, I'm using Hapi.js. The request stream can be accessed via request.raw.req
. My code looks like this:
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();
Upvotes: 1
Views: 2018
Reputation: 1410
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.
Upvotes: 1