Say I create a buffer from a string:
let buf = Buffer.from('a test');
What is a good way to pad buf (with zeros or nulls) to 32 bytes?
I can think of a couple of options:
You could pad the string before using from:
const buf = Buffer.from(theString.padEnd(32, "\0"));
Note that if the string's length is greater than 32, the buffer's will be as well.
If theString is "example" (for instance), you end up with these bytes in the buffer:
65 78 61 6d 70 6c 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
alloc and copyAlternatively, alloc and copy:
const buf = Buffer.alloc(32, 0);
Buffer.from(theString).copy(buf);
Note that only as many bytes as will fit are copied (it doesn't throw if the string is longer, it just leaves off the end).
You can also use Buffer.concat() for this purpose:
let buf = Buffer.from('a test');
const totalLength = 32;
const result = Buffer.concat([buf], totalLength);
console.log('Result length:', result.length);
console.log('Result:', result);
This will output something like:
Result length: 32
Result: <Buffer 61 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00>