Gausie
Gausie

Reputation: 4359

Buffer length smaller than expected

I'm creating a Buffer from a long string of hex but getting some size mismatching (when I try to decrypt it). Sure enough when I run the following code:

var hexData = fs.readFileSync(fileName).toString().trim();
var bufferData = new Buffer(hexData, 'hex');

console.log(Buffer.byteLength(hexData, 'hex'));
console.log(bufferData.length);

my output is:

232548

30

Why is the whole string not being loaded into the Buffer?

EDIT: I noticed I was being silly and should be doing

var bufferData = fs.readFileSync(fileName, 'hex');

But the length of that is 930194!

Upvotes: 2

Views: 1398

Answers (1)

Ahmed Fasih
Ahmed Fasih

Reputation: 6927

Assuming you meant hexData and not data when you build bufferData, Buffer.byteLength seems to happily accept malformed hex, whereas the Buffer constructor will strip it out of the buffer. Consider:

> Buffer.byteLength('ff00junk', 'hex')
4
> var b = new Buffer('ff00junk', 'hex')
> b.length
2
> b
<Buffer ff 00>

Perhaps your file contains invalid hex?

Upvotes: 2

Related Questions