I have client - server application, server side on Node.js client on flash, communicating with each other by socket. I write stringifyed JSON to socket, and on server read data:
socket.on('data', function(data) {
console.log(JSON.parse(data.toString());
var json = JSON.parse(data.toString()) });
Everything was OK, until I started to send to server JSON with long text messages containing '\n\r'. On that I getting error:
SyntaxError: Unexpected end of input
because '\n\r' means end of the pack. Delete '\n\r' from text isn't the good way cause I need it to show text correctly. Please give me best way to deal with that problem. Thanks in advance.
use JSON.stringify(data)
instead of .toString()
One easy way would be to try
to parse, if not, then wait for more data:
var json = '';
socket.on('data', function(data) {
try {
json = JSON.parse(data);
} catch (e) {
json += data;
try {
json = JSON.parse(json);
// Now it's fine.
} catch (e) {
// Wait for more.
return;
}
}
// Now it's fine.
// At the end do;
json = '';
});