Uplink message is saved as "[object Object]" in Node.js


(Smitae) #1

I am playing a bit with node.js to get data from my ttn application. Sorry, I am not a java developer, so maybe I am missing something?

I use the example node.js from the ttn website. But I run in problems;

My code (well the part which I do not understand);

 ttn.data(appID, accessKey)
  .then(function (client) {
    client.on('message', function (devID, message) {
      console.log("Received uplink from ", devID)
      console.log(message)
      message: message.toString()  (This I also left out, but same effect)
      	fs.appendFile('sensor_data.txt', devID, function (err) {})
        fs.appendFile('sensor_data.txt', message, function (err) {})
    })
  })

console.log indeed shows the devID and the message as expected.
So I would assume devID and message can be used.

devID is indeed added to the File. But message is something like [object Object] so not what I expected, why does console.log shows the “message”? But there is nothing when I try to add it to the File?
Why does this happen?
I think my java skills need an update…

Any idea how to fix this?


(Arjan) #2

Your message parameter is not some text, but a JavaScript object which has many attributes/ properties. (It might even have its own functions to work on itself.) To help you debugging, Node.js console.log makes a best guess as for what you want, and prints the object’s attributes in some human readable format. But when writing things to a file, you need to be far more explicit about what you need.

The documentation states:

See The MQTT API Reference for more information about these events and what their payloads look like.

Looking at that, you’d need something like message.payload_raw to see the Base64 encoded raw payload, or message.payload_fields.myField if you’re using some payload functions in TTN Console.

If you want to store all that’s in the message, you could use JSON.stringify(message).

And:

I think my java skills need an update…

…you won’t find good answers when searching for Java, as Node.js is not Java but JavaScript.

message: message.toString() (This I also left out, but same effect)

This is not a variable assignment, so won’t change message. And it obviously does not compile the way you pasted it here. Please always paste real code. And finally, pleas see How do I format my forum post?


(Smitae) #3

Thanks, this helps, I thought it was some kind of object. I did not know console.log was just doing some guessing, that caused the Confusion.

Node.js is JavaScript, I knew that :slight_smile:


(Chris) #4

Worth noting that there is a new version of the JS SDK in which in the api has changed a bit.