Node.js: MessagePack serialization

Introduction

In this tutorial we will learn how to serialize content to the MessagePack format, using Node.js.

We will be using this library, which you can install with the following npm command:

npm install msgpack

For this introductory tutorial we will serialize a very simple JavaScript object, representing a sensor measurement.

The code

The first thing we will do is importing the newly installed module.

const msgpack = require('msgpack');

Then we will declare a JavaScript object, which we will later serialize. For testing purposes, we will assume an object representing a sensor measurement from a humidity sensor.

const toSerialize = {
     sensorType: "humidity",
     sensorValue: 10
};

Then, to do the serialization to the MessagePack format we simply need to call the pack method. This method receives as argument a JavaScript object and outputs the serialized content, as a Buffer object [1].

Thus, we will pass as input our previously created object and store the result in a variable.

const serialized = msgpack.pack(toSerialize);

To finalize, we will print the result to the console.

console.log(serialized);

The final code can be seen below.

const msgpack = require('msgpack');

const toSerialize = {
     sensorType: "humidity",
     sensorValue: 10
 };

const serialized = msgpack.pack(toSerialize);

console.log(serialized);

Testing the code

To test the code, simply run it using a tool of your choice. In my case, I’m using Visual Studio Code with the Code Runner extension.

You should get an output similar to figure 1. As can be seen, we have obtained the serialized version of our JavaScript object, as expected. Note that each byte of the result is being represented in hexadecimal format.

Output of the program, tested on Visual Studio Code, showing the MessagePack payload obtained.
Figure 1 – Output of the program, showing the serialized content.

To confirm we have obtained the correct payload, we can use this online tool to test it. On the left text box, place the JavaScript object from the code, formatted as JSON. This is illustrated in figure 2.

Note that in JavaScript we don’t need to use “” around the field names when declaring objects, but in JSON we do.

On the right side, on the top of the text box, make sure the HEX option is selected. Then, click the “encode” button to obtain the expected MessagePack payload.

As can be seen in figure 2, we obtain the same bytes we did when running the JavaScript code, as expected.

Using an online tool to obtain the expected MessagePack payload,
Figure 2 – Confirming the expected MessagePack payload, using an online tool.

Suggested readings

References

[1] https://github.com/msgpack/msgpack-node

Leave a Reply