0

I am doing a COAP service call using the following code segment and getting the response. According to the code, I can print the response in the log.

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

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

I need to get the response string to a variable for further processing. I tried console.log(res) and got following on the log where I cannot find the response string in. How can I get the response string (body) to a variable instead of printing it on the log? I think it is wrapped inside payload. I need it as a string.

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 }
Malintha
  • 4,512
  • 9
  • 48
  • 82
  • What's a `response string`? – Liam Aug 07 '18 at 10:51
  • You need to read the payload. How you do that should be covered by the documentation. Once you've read the payload, these questions and their answers may be useful: [1](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call), [2](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – T.J. Crowder Aug 07 '18 at 10:53
  • @Liam body of the response – Malintha Aug 07 '18 at 10:56
  • I am not really getting the reason for down-voting this question – Malintha Aug 07 '18 at 10:57
  • 1
    Well I for one am really not clear what your question is? Are you asking how to access properties of the object? Have you checked `process.stdout.IncomingMessage`..etc? – Liam Aug 07 '18 at 11:01
  • I tried it and also `res.IncomingMessage` which give me `undefined`. – Malintha Aug 07 '18 at 11:19

1 Answers1

1

Your response is a stream. You can read a stream into a string by read()ing it:

req.on('response', function(res) {
  let result = res.read().toString();
  console.log(result);
});
Markus Dresch
  • 5,290
  • 3
  • 20
  • 40