The following code in node.js does not log all incoming data inside the brackets, rather, it breaks the data into chunks. So for example, if the incoming data is ABCDEF...XYZ it logs the data as [ABC][DEF]...[XYZ] rather than [ABCDEF...XYZ]. The data is much larger of course, the alphabet is just an example.
How should I write this so that all incoming data is logged once inside the brackets and not in parts?
chatServer.on('connection', function(client)
{
client.on('data', function(data)
{
console.log('[' + data.toString() + ']');
})
})
Well your data is arriving in packets, so (in this case) you should be concatenating the packets into a variable that you define outside the function.
buffer = '';
chatServer.on('connection', function(client)
{
client.on('data', function(data)
{
buffer += data.toString();
})
});
console.log('[' + buffer + ']');
Like matthewdavidson said, you are subscribing to every "chunk" of data that is sent rather than the whole message. It is more likely you want to capture the data in a closure within the function and still respond asynchronously. Try the following:
chatServer.on('connection', function(client)
{
var buffer = '';
client.on('data', function(data)
{
buffer += data;
})
client.on('end' function(){
console.log('[' + buffer + ']');
})
});
Checkout http://www.nodebeginner.org/#handling-post-requests for more information