从node.js中的websocket数据馈送读取JSON数组

时间:2016-12-28 23:14:47

标签: node.js

我是javascript和编码的初学者。 我试图做的是从这个websocket数据源中获取出价(数组),但是我在我的代码中苦苦挣扎,我尝试仅打印(console.log)" bidPrice& #34;而不是其他所有类似" asksize"," bidize"等等 当我运行我的代码时,我只得到未定义而不是" bidPrice", 这里缺少什么? 谢谢你的帮助

这里的结果(cmd),当我运行代码不好!!!!

C:\Users\Desktop\codesource>node wss.js
Connection opened
undefined
undefined
undefined

这是我在node.js中的代码:

fs = require('fs');
var WebSocket = require('ws');
var ws = new WebSocket('wss://www.bitmex.com/realtime');
ws.on('open', function() {
    console.log('Connection opened');

    //out
    ws.send(JSON.stringify({"op": "subscribe", "args": ["quote:XBTUSD"]}));



});
//in            
ws.on('message',function(message){var response = JSON.parse(message) 

 fs.writeFile('helloworld.txt', JSON.stringify(message));
 fs.writeFile('helloworld.json', JSON.stringify(message));


    var data = message;

    var json = JSON.parse(data);

    console.log(json["bidPrice"]);

});

这里是来自bitmex websocket的数据

Connection opened
{ info: 'Welcome to the BitMEX Realtime API.',enter code here
  version: '1.2.0',
  timestamp: '2016-12-28T22:27:15.000Z',
  docs: 'https://www.bitmex.com/app/wsAPI',
  heartbeatEnabled: false }
{ success: true,
  subscribe: 'quote:XBTUSD',
  request: { op: 'subscribe', args: [ 'quote:XBTUSD' ] } }
{ table: 'quote',
  keys: [],
  types:
   { timestamp: 'timestamp',
     symbol: 'symbol',
     bidSize: 'long',
     bidPrice: 'float',
     askPrice: 'float',
     askSize: 'long' },
  foreignKeys: { symbol: 'instrument' },
  attributes: { timestamp: 'sorted', symbol: 'grouped' },
  action: 'partial',
  data:
   [ { timestamp: '2016-12-28T22:26:54.645Z',
       symbol: 'XBTUSD',
       bidSize: 12,
       bidPrice: 969.59,
       askPrice: 971.06,
       askSize: 499 } ] }

它似乎也不起作用

console.log(response.data[0].bidPrice);


Connection opened
C:\Users\jalal\Desktop\codesource\wss.js:24
        console.log(response.data[0].bidPrice);
                                 ^

TypeError: Cannot read property '0' of undefined
    at WebSocket.<anonymous> (C:\Users\jalal\Desktop\codesource\wss.js:24:27)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:191:7)
    at Receiver.ontext (C:\Users\jalal\Desktop\codesource\node_modules\ws\lib\WebSocket.js:841:10)

1 个答案:

答案 0 :(得分:1)

更改

console.log(json["bidPrice"]);

console.log(response.data[0].bidPrice);

仅供参考,您不需要变量datajson