1

I have a buffer which is being populated with a bunch of base64 strings. I want a way to decode those string and be able to read all of the base64 strings in that buffer.

const slugId1 = 'YriU6QbcQj6xtdUUosJTxA==';
const slugId2 = 'Su7Zvq1vRca/teTNfEmfNQ==';
const SLUGID_SIZE = 16;

let buffer = Buffer.alloc(SLUGID_SIZE * 2);

buffer.write(slugId1, 0, SLUGID_SIZE, 'base64');
buffer.write(slugId2, SLUGID_SIZE, SLUGID_SIZE, 'base64');

console.log(buffer.toString('base64', 0, SLUGID_SIZE));
console.log(buffer.toString('base64', SLUGID_SIZE, SLUGID_SIZE));

What I'm getting:

YriU6QbcQj6xtdUUosJTxA==

What I expect to get:

YriU6QbcQj6xtdUUosJTxA==
Su7Zvq1vRca/teTNfEmfNQ==

Any help is appreciated.

1
  • buffer.toString 2nd and 3rd parameter are start and end - given you give the same value for start and end, the result is of course zero length Commented Aug 30, 2017 at 4:14

1 Answer 1

3

try this

const slugId1 = 'YriU6QbcQj6xtdUUosJTxA==';
const slugId2 = 'Su7Zvq1vRca/teTNfEmfNQ==';
const SLUGID_SIZE = 16;

let buffer = Buffer.alloc(SLUGID_SIZE * 2);

buffer.write(slugId1, 0, SLUGID_SIZE, 'base64');
buffer.write(slugId2, SLUGID_SIZE, SLUGID_SIZE, 'base64');

console.log(buffer.toString('base64', 0, SLUGID_SIZE));
console.log(buffer.toString('base64', SLUGID_SIZE, SLUGID_SIZE * 2));

buffer.toString() - third argument is not length, it is end offset.

Sign up to request clarification or add additional context in comments.

2 Comments

buffer.write() - third argument is not length, it is end offset - no, for write it is a length - see documentation - you could actually do buffer.write(slugId2, SLUGID_SIZE, 'base64'); - because the length defaults to buffer.length - offset - in this case, it would be SLUGID_SIZE
Yup, that did it. Thanks for the quick response!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.