Binary encoding deprecation in Node.js

Recently I had to implement an endpoint for an archaic API in Node.js, which required some binary manipulation.

Giving a quick peak at documentation, you will see that binary encoding should be avoided at all costs and is already deprecated, instead you should rely on buffers.

Here goes a really basic and quick example doing the same thing using encoding and then using buffers.

What you should NOT be doing:

stream.write(utils.pack('N', payload.data.length + 4) + payload.data,
 'binary', payload.callback);

Instead you should be doing:

var myb = new Buffer(payload.data.length + 4);
myb.writeUInt32BE((payload.data.length + 4), 0);
myb.write(payload.data, 4);
stream.write(myb, payload.callback);

Realize that when you use a buffer in the write method, encoding does not fallback to utf8 by default.

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s