Q:

Can't send data over serialPort

I would like to control my Arduino robot with Node.js and a joystick, but  serialport.write doesn't send any data to Arduino. I have tried to use code without a joystick and it works but only with one serial.write.
Is there a bug in my code?
Arduino code:
String data = Serial.readString();
Serial.println(data);
if(data=="2") {
  //motor1
}

Node.js  
var hid = require('node-hid');
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('COM3', {
  baudrate: 9600
});
serialPort.on("open", function() {
  console.log('open');
  function sentData(data) {
    console.log(data);
    if (data == 0)
      setTimeout(function() {
        serialPort.write('1')
      }, 2000);
    else if (data > 999)
      setTimeout(function() {
        serialPort.write('2')
      }, 2000);
  }
  var device = new hid.HID(1133, 49685);
  device.on('data', function(buf) {
    var ch = buf.toString('hex').match(/.{1,2}/g).map(function(c) {
      return parseInt(c, 16);
    });
    var position = ((ch[2] & 0x0f) << 6) + ((ch[1] & 0xfc) >> 2);
    position = parseInt(position);sentData(position);
  });
});

A:

The arduino code should look like this:
String data = '';
while(Serial.available() > 0) {
    data = data + Serial.read();
}
Serial.println(data);
if(data == "2") {
     //code
}

But, sorry, I can't see if there is problem in you node.js

