node.js服务器并不总是清除先前运行的数据

时间:2016-09-27 23:27:25

标签: node.js reset clear

我是node.js(或者一般的javascript)的新手,并且不确定这里发生了什么。有时当我运行我的node.js服务器时,它在启动时就开始打印上次运行时的数据。是否有什么东西可以保留重置新运行的一切?我有连接到此服务器的arduino XBee节点。这是我的node.js代码:

var SerialPort = require("serialport");
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var ON_DEATH = require('death');

// Set up serial port 
var portName = process.argv[2],
portConfig = {
    baudRate: 9600,
    parser: SerialPort.parsers.readline("\n")
};
var sp = new SerialPort(portName, portConfig); // got rid of deprecation issue with sp4

// Respond with file when a GET request is made to the homepage: app.METHOD(PATH, HANDLER) '/'=homepage
app.get('/', function(req, res){
    res.sendfile('index.html');
});             

// Listen on the connection event for incoming sockets, and log it to the console.
io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function(){
    });
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
        sp.write(msg + "\n");
    });
});

// Make the http server listen on port 3000
http.listen(3000, function(){
    console.log('listening on *:3000');
});

/////////////////////////////////////////////////////////////////////////////////////////////////

sp.on("open", function (err) {
    if (err) 
        return console.log('Error opening port: ', err.message);
    console.log('open');

    // INFO VARIABLES
    //var nodeCount = 0;
    var pendingNodes = [];
    var connectedNodes = [];
    var buffer0;
    var nodeInfo;   

    // Cleanup when termination signals are sent to process
    ON_DEATH(function(signal, err) {
        var death_msg = "Q";
        sp.write(death_msg);
        sp.close();     
        // zero out all variables
        pendingNodes = [];
        connectedNodes = [];
        buffer0 = [];
        nodeInfo = [];

        console.log("\n\nSending reset signal to nodes.\n\n")
        sp.flush(function(err,results){});
        process.exit();
    })

    // listen for data, grab time, delimit
    sp.on('data', function(data) {
    var time = new Date();
    buffer0 = data.split('\n'); // array of data till newline
    // Split again into either "#ID" into [#ID] (if new broadcast), or "#ID Data" into [#ID, Data] (preconnected node)
    nodeInfo = buffer0[0].split('   ');
    //console.log("     nodeInfo: " + nodeInfo);

    // DEBUGGING PRINT -- DELETE LATER
    //console.log("     pendingNodes: " + pendingNodes + "     connectedNodes: " + connectedNodes);


////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // Receiving ID or [ID, Data] -- Testing all possible cases

    // if first char 
    if (nodeInfo[0][0] == "#") { // could check up here for && no temp data too 

        // Brand new node (ID not in pendingNodes or connectedNodes)
        if ((pendingNodes.indexOf(nodeInfo[0]) == -1) && (connectedNodes.indexOf(nodeInfo[0]) == -1)) {
            console.log("Brand new node: " + nodeInfo[0])
            pendingNodes.push(nodeInfo[0]);

        }


        // Pending node (ID in pendingNodes, but not in connectedNodes)
        else if ((pendingNodes.indexOf(nodeInfo[0]) != -1) && ((connectedNodes.indexOf(nodeInfo[0]) == -1))) {
            console.log("  Pending node: " + nodeInfo[0])

            // send back ID to confirm handshake
            sp.write(nodeInfo[0]);
            // Remove from pendingNodes
            var index = pendingNodes.indexOf(nodeInfo[0]);
            if (index > -1) {
                pendingNodes.splice(index, 1);
            }
            // Add to connectedNodes
            //var 
            connectedNodes.push(nodeInfo[0]);


        }
        // Connected node (ID in connectedNodes, but not in pendingNodes)
        else if  ((pendingNodes.indexOf(nodeInfo[0]) == -1) && (connectedNodes.indexOf(nodeInfo[0]) != -1)) {
            console.log("    Connected node: " + nodeInfo[0] + "   " + nodeInfo[1]);

            // Disconnect nodes with undefined temperatures to force restart
            if (typeof nodeInfo[1] == 'undefined') {
                console.log("Undefined data for node: " + nodeInfo[0] + ". Dropping connection to this node.");
                var index = connectedNodes.indexOf(nodeInfo[0]);
                if (index > -1) {
                    connectedNodes.splice(index, 1);
                }

            }

            //var t = time.getTime();

            // FIRST: fix bug -- sometimes temp showing as undefined            
            // Then:
            // Update data properly
            // Average data
            // add 3rd element to nodes for time stamp, check that all timestamps are recent periodically
            // Detect drop-offs and remove nodes

        }
        // Error (ID in both pendingNodes and connectedNodes [should not happen])
        else {
            console.log("Error: node exists in both pending and connected.")

        }


    }
    else if (nodeInfo[0][0] != "#") {
        // FOR DEBUGGING PURPOSES, DELETE LATER
        console.log("Error 2: incoming data does not start with '#'.")
    }



    /* // placeholders for functionality to add
    var CalcAverage = function() {
        console.log("CalcAverage: * every 1 second(s) *");
    }
    setInterval(function(){ CalcAverage() },2000);  


    var CheckNodes = function() {
        console.log("CheckNodes: * every 6 second(s) *");
    }
    setInterval(function(){ CheckNodes() },6000);
    */



    }); // end data
}); // end open 

以下是以某种方式显示旧节点数据的示例:

enter image description here

1 个答案:

答案 0 :(得分:0)

一些可能性:

来自客户端的旧(或您不知道发送的新数据)数据已在串口缓冲,或者socket.io在客户端浏览器上自动重新连接并开始发送数据,即使您没有与客户端浏览器网页进行交互。