2015-06-26 61 views
0

我正在嘗試處理我在端口中獲得的數據。我的代碼:節點js websock進程

var WebSocketServer = require('ws').Server, wss = new WebSocketServer({ port: 5678 }); 

wss.on('connection', function connection(ws) { 
    ws.on('message', function incoming(message) { 

     function time_m() { 
      var my_month=new Date() 
      var month_name=new Array(12); 
      month_name[0]="JAN" 
      month_name[1]="FEB" 
      month_name[2]="MAR" 
      month_name[3]="APR" 
      month_name[4]="MAY" 
      month_name[5]="JUN" 
      month_name[6]="JUL" 
      month_name[7]="AUG" 
      month_name[8]="SEP" 
      month_name[9]="OCT" 
      month_name[10]="NOV" 
      month_name[11]="DEC" 
      return month_name[my_month.getMonth()];  
     } 
     function acc_array (n) { 
      var arr_acc = new Array ("xAxis", "yAxis", "zAxis"); 
      return arr_acc[n]; 
     } 
     function SOSjson() { 

      function formatDate(d) { 
       return d.getDate() + '-' + (time_m()) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ":" + d.getMilliseconds() +" IST"; 
      } 

      var SOSJSONObj = {}; 
      var observations = []; 
      var record = []; 
      var output = []; 
      var version = "1.0.1"; 
      var sensor = "MySensor"; 
      var starttime; 
      var name; 
      var value; 
      SOSJSONObj.version = version; 
      SOSJSONObj.observations = observations; 
      observations[0] = {sensor, record}; 
      var i; 
      var msg = []; 
      msg = message; 
      console.log("Reading array value of messgae"); 
      console.log(msg[0]); 

      for (i = 0; i < 3; i++) { 
       //sleep(100); 
       name = acc_array (i); 
       value = msg; 
       output.push({name, value}); 
       starttime = formatDate(new Date()); 
       record.push({starttime, output}); 
      } 

      return JSON.stringify(SOSJSONObj); 
     } 

     console.log('received: %s', message); 
    }); 
    SOSjson(); 
    ws.send('something'); 
}); 

但它表明:

/home/root/node_modules/ws/websock_01.js:43 
      observations[0] = {sensor, record}; 
            ^
    SyntaxError: Unexpected token , 
     at Module._compile (module.js:439:25) 
     at Object.Module._extensions..js (module.js:474:10) 
     at Module.load (module.js:356:32) 
     at Function.Module._load (module.js:312:12) 
     at Function.Module.runMain (module.js:497:10) 
     at startup (node.js:119:16) 
     at node.js:906:3 

我無法找到它遇到的問題。節點js不處理我的數據。這個函數調用我猜想不能正常工作。否則聲明可能不正確。

回答

0

字符串observations[0] = {sensor, record};是不正確的,如果你想要一個對象,那麼應該是這樣的: observations[0] = {sensor : sensor, record : record}; 或數組:observations[0] = [sensor, record]; 但在你的情況下,最好使用一個對象