Yvann Argentin
Yvann Argentin

Reputation: 83

Data and string comparison with nodejs

I'm a beginner with node.js and I'm willing to create a TCP server which would give me different answers depending on what it receives.

Here's the server side :

var net = require('net');

var server = net.createServer(function(c) {
    console.log('socket opened');
    c.setEncoding('utf8');
    c.on('end', function() {
        console.log('connection/socket closed');
    });
    c.on('data', function(data) {
        console.log('Data:'+data);
        if(data.toString() == "open"){
            c.write('Answer: opened');
        }else if(data.toString() === "add"){
            c.write('Answer: added');
        }else if(data.toString() === "process"){
             c.write('Answer: processed');
        }
    });
});

server.listen(8080, function() { // start server (port 8080)
    console.log('server started');
});

I simply use telnet to try and see if my code is working. Basically I want the server to answer 'opened' if I send him 'open', 'added' if I send 'add' ... I don't know why but it wont work. I've been trying for an hour already and I'm sure that must be some simple mistake I made but now I can't see anything that would cause this simple echo server not to work properly.

Upvotes: 6

Views: 81667

Answers (3)

Rohit Jangid
Rohit Jangid

Reputation: 2605

String comparison and response in html(javascript)

var diff_match_patch = require('googlediff');
var dmp = new diff_match_patch();

function compareString(){
    var leftHandSideObject = JSON.stringify(req.body[0]);
    var rightHandSideObject = JSON.stringify(req.body[1]);
    var ms_start = (new Date()).getTime();
    var d = dmp.diff_main(leftHandSideObject, rightHandSideObject);
    var ms_end = (new Date()).getTime();
    if (true) {
        dmp.diff_cleanupSemantic(d);
    }
    res.status(200).json(ds);
}

Upvotes: 0

dboshardy
dboshardy

Reputation: 522

I know it's later, but there is a better answer, and I found this googling a similar problem. So here are my 2 cents.

To properly catch all cases (and not just the quirks specific to this single case) you should just use the trim() method

if (data.toString().trim() === 'open') {
    //...
}

Upvotes: 32

bnuhero
bnuhero

Reputation: 2734

Your code is OK. When you use telnet, you send text messages out by hitting ENTER key. The text received by the sever ends with '\r\n'. So you should compare two strings like this:

if (data.toString() === 'open\r\n') {
  //...
}

Upvotes: 1

Related Questions