node.js + serial code not work consistently
<p>i tried to calculate root mean square using node.js, trying to be smart to make some kind of high resolution realtime measurement of stuff from serial port. </p>

<p>the code doesnt really matter. but each time i try to run this multiple times but it output totally different rms output value, sometimes very big, sometimes very small, NaN, etc.
the question is:
why? how? is there any node.js quirk i miss? like inter-process shared memory allocation? </p>

<p>it's fixed after i rewrite the program(some edit) or waiting for some time</p>

<p>re running a program should do the same thing everytime, right?</p>

<p>btw i'm using nodeserial for serial communication, at 500k baud</p>

<p>actual code may be posted later if you want</p>

<p>edit: the code</p>



<pre class="lang-js prettyprint-override"><code>var math = require('mathjs');

var fs = require('fs');

// serving the static html "client"
var http = require('http');
var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');
var serve = serveStatic("./");
var server = http.createServer(function(req, res) {
  var done = finalhandler(req, res);
  serve(req, res, done);
});
//  socket.io

var app = require('express')();
var http2 = require('http').Server(app);
var io = require('socket.io')(http2);

io.on('connection', function(socket) {
  console.log('client connected');
});

/* CONSOLE INTERFACE, USED TO MANUALLY INSERT SOME KIND OF VARIABLES*/
//stdin interaction
var stdin = process.openStdin();
var command = '';
var commandmode = false;
var bufferdata;
var command = 0;

//serial stuff

var serialport = require('serialport');
var SerialPort = serialport.SerialPort;
//portName = process.argv[2];
portName = "COM4"
  //parsing commandline argument as comport name


var myPort = new SerialPort(portName, {
  baudRate: 500000, // choose between: 115200, 57600, 38400, 19200, 9600, 4800, 2400, 1800, 1200, 600, 300, 200, 150, 134, 110, 75, or 50
  // look for return and newline at the end of each data packet:
  parser: serialport.parsers.readline("\n")
});

myPort.on('open', showPortOpen);
myPort.on('data', sendSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);

var datacount = 0;

function showPortOpen() {
  console.log('port open. Data rate: ' + myPort.options.baudRate);
}

var timestamp;
var timestampold;
var dt;

function pad(num, size) {
  var s = "0000" + num;
  return s.substring(s.length - size);
}

function padd(num, size) {
  var s = "00000000" + num;
  return s.substring(s.length - size);
}

var vrms = [];
var irms = [];
var torq = [];
var speed = [];
var vraw = [];
var iraw = [];

function sendSerialData(data) {
  if (datacount === 0) {
    timestampold = Date.now();
  }
  if (datacount === 10) {
    console.log(data);
  }
  if (datacount === 1000) {
    timestamp = Date.now();
    dt = timestamp - timestampold;
    var samplerate;
    var datalength = data.length + 1;
    samplerate = datacount * 1000 / dt;
    var troughput = datalength * samplerate;
    var troughputp = 800 * troughput / 500000;
    console.log(datacount + " data has been recorded. time elapsed:" + dt + ", samplerate:" + samplerate + " troughput:" + troughput + "/" + troughputp + "%");
  }

  var parseddata = data.split(",");
  vraw.push(parseInt(parseddata[0], 16));
  iraw.push(parseInt(parseddata[1], 16));
  torq.push(parseInt(parseddata[2], 16));
  speed.push(parseInt(parseddata[3], 16));
  rmsfast(vraw[datacount], iraw[datacount]);
  //var rawlog = padd(datacount,8) + "," + pad(vraw[datacount],4) + ","+ pad(iraw[datacount],4) +","+ pad(speed[datacount],4)+","+ pad(torq[datacount],4);
  //var rawlog = padd(datacount, 8) + "," + vraw[datacount] + "," + iraw[datacount] + "," + speed[datacount] + "," + torq[datacount] + "&gt;&gt;" + vrms[datacount] + "," + irms[datacount];
  //fs.appendFileSync('raw.txt', rawlog);
  //console.log(rawlog);

  ++datacount;
}

function showPortClose() {
  console.log('port closed.');
}

function showError(error) {
  console.log('Serial port error: ' + error);
}

var varray = [0];

// zero setup;

var mid = 2048; //ideal; changed on zerocross detection

/* the data from microcontroller is as such: VVV,III,TTT,NNN
CC = COMMAND/RUNNING MODE
VVVV = VOLTAGE READING
IIII = CURRENT READING
TTTT = TORQUE READING
NNNN = SPEED (RPM) READING
Z = IS ZERO(0=false,1=voltage,2=current)
delta t between data (microsecond);
 */
var bufferV = [0];
var bufferI = [0];
var datacount;

var dataindex; // index of data called on the below stuff

var rmslength = 80;
var sigmaVsquared = 0;
var sigmaIsquared = 0;

var lastVvalue = 0;
var lastIvalue = 0;
var Vrms = 0;
var avgV = 0;
var avgI = 0;

function rmsfast(newVoltage, newCurrent) { // example use = rmsfast(data,buffer,)
  var newSqVoltage = Math.pow(newVoltage, 2);
  var newSqCurrent = Math.pow(newCurrent, 2);


  bufferV.push(newSqVoltage);
  if (bufferV.length === 80) {
    lastVvalue = bufferV.shift();
  } else {
    //lastVvalue = newSqVoltage;
  }
  avgV += ((newSqVoltage - lastVvalue) / 80);
  Vrms = math.sqrt(avgV);

  bufferI.push(newSqCurrent);
  lastIvalue = bufferI.shift();
  avgI += (newSqCurrent - lastIvalue) / 80;
  var Irms = math.sqrt(avgI);
  var darn = math.sqrt(4000000);

  if (datacount &lt; 1000) {
    var darz = Number.isInteger(newSqVoltage);
    var vavg = avgV;
    var vrmss = vrms;
    console.log(newVoltage + "\t---" + avgV + "\t---" + Vrms);
  }
  if (datacount === 1000) {
    myPort.close(process.exit());


  }

  vrms.push(Vrms);
  irms.push(Irms);
}
server.listen(2000); // listening to the port

stdin.addListener("data", function(cons) { //"listening" to stdin
  command = cons.toString().trim();
});
</code></pre>