David Powell
David Powell

Reputation: 547

What encoding does Javascript fs.readFileSync return?

Consider the following Node.js Javascript program:

var fs = require('fs');
var encoding1='?';
var encoding2='?';
var a = fs.readFileSync('./testdoc.pdf');
var b = new Buffer(fs.readFileSync('./testdoc.pdf',encoding1),encoding2);
console.log(a===b);

To what values must the encoding1 and encoding2 variables be set in order for true to be printed at the console?

Upvotes: 2

Views: 13675

Answers (1)

rsp
rsp

Reputation: 111434

You need a.equals(b)

For binary data like PDF you should use the "binary" encoding but no encoding will make any two buffers equal with the === operator so a === b will always give you false. You need to use a.equals(b) to test if two buffers have the same contents.

See buf.equals(otherBuffer) in the docs:

Example

See this code:

var fs = require('fs');
var encoding1 = 'binary';
var encoding2 = 'binary';
var a = fs.readFileSync('./testdoc.pdf');
var b = new Buffer(fs.readFileSync('./testdoc.pdf', encoding1), encoding2);
console.log('Object equality:', a === b);
console.log('Buffer equality:', a.equals(b));

It will print:

Object equality: false
Buffer equality: true

Upvotes: 5

Related Questions