将服务调用的响应放入变量

时间:2018-08-07 10:49:54

标签: javascript

我正在使用以下代码段进行COAP服务调用并获得响应。根据代码,我可以在日志中打印响应。

var req = coap.request('coap://localhost/hello')

req.on('response', function(res) {
res.pipe(process.stdout);
});

我需要将响应字符串转换为变量以进行进一步处理。我尝试了console.log(res)并在无法找到响应字符串的日志上进行了跟踪。如何将响应字符串(body)获取到变量中,而不是将其打印在日志中?我认为它包装在payload中。我需要它作为字符串。

IncomingMessage {
  _readableState: 
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: [],
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  payload: <Buffer 48 65 6c 6c 6f 20 74 68 65 72 65>,
  options: [],
  code: '2.05',
  method: undefined,
  headers: {},
  url: '/',
  rsinfo: { address: '127.0.0.1', family: 'IPv4', port: 5683, size: 20 },
  outSocket: { address: '0.0.0.0', family: 'IPv4', port: 41185 },
  _packet: 
   { code: '2.05',
     confirmable: false,
     reset: false,
     ack: true,
     messageId: 24618,
     token: <Buffer d8 41 e0 57>,
     options: [],
     payload: <Buffer 48 65 6c 6c 6f 20 74 68 65 72 65> },
  _payloadIndex: 0 }

1 个答案:

答案 0 :(得分:1)

您的回复是一条流。您可以通过read()将流读取为字符串:

req.on('response', function(res) {
  let result = res.read().toString();
  console.log(result);
});