5

I used the code below to encode a file to base64.

var bitmap = fs.readFileSync(file);
return new Buffer(bitmap).toString('base64');

I figured that in the file we have issues with “” and ‘’ characters, but it’s fine with "

When we have It’s, node encodes the characters, but when I decode, I see it as It’s

Here's the javascript I'm using to decode:

fs.writeFile(reportPath, body.buffer, {encoding: 'base64'}

So, once the file is encoded and decoded, it becomes unusable with these funky characters - It’s

Can anyone shed some light on this?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
user3439399
  • 195
  • 1
  • 3
  • 13

3 Answers3

8

This should work. Sample script:

const fs = require('fs')
const filepath = './testfile'
//write "it's" into the file
fs.writeFileSync(filepath,"it's")

//read the file
const file_buffer  = fs.readFileSync(filepath);
//encode contents into base64
const contents_in_base64 = file_buffer.toString('base64');
//write into a new file, specifying base64 as the encoding (decodes)
fs.writeFileSync('./fileB64',contents_in_base64,{encoding:'base64'})
//file fileB64 should now contain "it's"

I suspect your original file does not have utf-8 encoding, looking at your decoding code: fs.writeFile(reportPath, body.buffer, {encoding: 'base64'})

I am guessing your content comes from a http request of some sorts so it is possible that the content is not utf-8 encoded. Take a look at this: https://www.w3.org/International/articles/http-charset/index if charset is not specified Content-Type text/ uses ISO-8859-1.

MatijaG
  • 818
  • 1
  • 9
  • 12
  • thankyou for pointing me to the right direction. I had to first remove the non standard ascii characters which are apostrophes (single and double) and then encode to base 64. – user3439399 Jun 27 '17 at 02:12
3

Here is the code that helped.

var bitmap = fs.readFileSync(file);

// Remove the non-standard characters
var tmp  = bitmap.toString().replace(/[“”‘’]/g,'');

// Create a buffer from the string and return the results
return new Buffer(tmp).toString('base64');
CodeWizard
  • 128,036
  • 21
  • 144
  • 167
user3439399
  • 195
  • 1
  • 3
  • 13
2

You can provide base64 encoding to the readFileSync function itself.

const fileDataBase64 = fs.readFileSync(filePath, 'base64')