Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding a file to base 64 Nodejs

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?

like image 567
user3439399 Avatar asked Aug 31 '26 13:08

user3439399


1 Answers

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.

like image 94
MatijaG Avatar answered Sep 03 '26 04:09

MatijaG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!