7

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.

2
  • 2
    There is deprecated binary encoding. But I would suggest to use base64 encoding Commented Jul 21, 2014 at 15:41
  • @AlexeyTen that is the right answer! Commented Sep 26, 2015 at 13:54

1 Answer 1

9

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');
Sign up to request clarification or add additional context in comments.

1 Comment

The answer seems to be outdated now. node.js printsDeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. new Buffer(s, 'binary') should be replaced with Buffer.from(s, 'binary'). nodejs.org/en/docs/guides/buffer-constructor-deprecation/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.