Arduino and JavaScript

My arduino is giving output according to this program - part of which is

Serial.print("A");
Serial.print(sensorValue);
Serial.print("B");
Serial.println();
Serial.print("C");
Serial.print(sensorValue1);
Serial.print("D");
Serial.println();

The output of which in the serial monitor of the arduino is shown as C491D A192B C49D A192B C484D A196B C482D A193B C483D A199B C485D A196B C486D A198B

Now my Node.js running the following code

var cleanData = ""; // this stores the clean data
var cleanData1 = "";
var readData = "";  // this stores the buffer
sp.on("data", function (data) { // call back when data is received
readData += data.toString(); // append data to buffer
// console.log(readData);
// if the letters "A" and "B" are found on the buffer then isolate what"s in the middle
// as clean data. Then clear the buffer.

if (readData.indexOf("D") >= 0 && readData.indexOf("C") >= 0) {
    cleanData1 = readData.substring(readData.indexOf("C") + 1, readData.indexOf("D"));
    readData = "";
    console.log(cleanData1);
   io.sockets.emit("message", cleanData1);
}
else if(readData.indexOf("B") >= 0 && readData.indexOf("A") >= 0)
{
    cleanData = readData.substring(readData.indexOf("A") + 1, readData.indexOf("B"));
    readData = "";
    console.log(cleanData);
    io.sockets.emit("message", cleanData);
}

});

The console reading of the same is not giving the desired results D A181B C D A181B C 181 462 181 462 181 462 181 462 181 462 462 462 462 462 462 462 462 462 462 462 462 462 462

From the console reading it is quite evident that the readings are not as desired . The reading should be one starting with 4 and another starting with 1. In fact there are console readings like

D A181B C D A181B C D A181B C D A181B C D A181B C

which should not be coming at all If I block one If statement block , then the readings shown by any one block is perfect.

Where am I going wrong?

It appears in you data event you are concatenating the new data but then you are checking the entire string (readData). So each time you check (setting cleanData) you are starting from the beginning and hitting the first result over and over.

Try chaning

readData += data.toString();

to

readData = data.toString();

This way you indexOf and substring matching will be looking at the new incoming data.