whiskers75
whiskers75

Reputation: 197

Node.JS Buffer has a newline after it

How do I remove the newline from this code?

socket.on('data', function(data){
    console.log('Data in server, sending to handle()');
    worker.handle(data, socket);
});

Worker.handle():

exports.handle = function handle(command, socket) {
console.log('Data sent to handle()');
command = command.toString();

console.log(command);

Edit:

I am getting this output:

test data
[newline]

Edit 2:

Here is the continuing code:

if (command === 'look') {
    //stuff
}
if (command === 'login') {
    //stuff

Upvotes: 2

Views: 7570

Answers (1)

Leon Stankowski
Leon Stankowski

Reputation: 408

This isn't a display / presentation problem. This is a problem related to data transmission protocols. Socket is a stream oriented protocol which means it isn't message based. Meanwhile you are using it like it is message based - which you can do but then you need to define a protocol for your sender and receiver to identify the start and end of each message.

Having said this and based on what you are asking I'm assuming that you've settled on using a newline (or some variant of one) as your message end marker. To make this work properly you need to actively look for that newline in the incoming data so you can recognize the end of each message as well as strip it off prior to processing.

The following code should replace your socket.on method to get the result you want.

// define your terminator for easy reference, changes
var msgTerminator = '\n';
// create a place to accumulate your messages even if they come in pieces
var buf;

socket.on('data', function(data){
    // add new data to your buffer
    buf += data;

    // see if there is one or more complete messages
    if (buf.indexOf(msgTerminator) >= 0) {
        // slice up the buffer into messages
        var msgs = buf.split(msgTerminator);

        for (var i = 0; i < msgs.length - 2; ++i) {
            // walk through each message in order
            var msg = msgs[i];

            // pick off the current message
            console.log('Data in server, sending to handle()');
            // send only the current message to your handler
            worker.handle(msg, socket);
        }

        buf = msgs[msgs.length - 1];  // put back any partial message into your buffer
    }
});

Upvotes: 3

Related Questions