Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js buffer string serialization

Tags:

node.js

I want to serialize a buffer to string without any overhead ( one character for one byte) and be able to unserialize it into buffer again.

var b = new Buffer (4) ;
var s = b.toString() ;
var b2 = new Buffer (s) 

Produces the same results only for values below 128. I want to use the whole scope of 0-255.

I know I can write it in a loop with String.fromCharCode() in serializing and String.charCodeAt() in deserializing, but I'm looking for some native module implementation if there is any.

like image 938
Krzysztof Wende Avatar asked Jul 21 '14 14:07

Krzysztof Wende


People also ask

How do I use serialization in node JS?

Create a file with the name "serialize. js" and copy the following code snippet. After creating the file, use the command "node serialize. js" to run this code.

How do I decode buffer data in node JS?

In Node. js, the Buffer. toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.

What does the BUF toJSON () method return in node JS?

The Buffer. toJSON() method returns the buffer in JSON format.

What is serialization and Deserialization in node JS?

Passport uses serializeUser function to persist user data (after successful authentication) into session. Function deserializeUser is used to retrieve user data from session.


1 Answers

You can use the 'latin1' encoding, but you should generally try to avoid it because converting a Buffer to a binary string has some extra computational overhead.

Example:

var b = Buffer.alloc(4);
var s = b.toString('latin1');
var b2 = Buffer.from(s, 'latin1');
like image 177
mscdex Avatar answered Oct 30 '22 09:10

mscdex