Latest and greatest way to do this:
Node supports file and buffer operations with the base64 encoding:
const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});
Or using the new promises API:
const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});
Answer from Mike Martin on Stack OverflowLatest and greatest way to do this:
Node supports file and buffer operations with the base64 encoding:
const fs = require('fs');
const contents = fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});
Or using the new promises API:
const fs = require('fs').promises;
const contents = await fs.readFile('/path/to/file.jpg', {encoding: 'base64'});
I think that the following example demonstrates what you need: I removed the link because it was broken.
The essence of the article is this code part:
var fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
// convert image to base64 encoded string
var base64str = base64_encode('kitten.jpg');
console.log(base64str);
// convert base64 string back to image
base64_decode(base64str, 'copy.jpg');
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.
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');
» npm install js-base64-file
» npm install file-base64
» npm install nodejs-base64-converter
Here's my very slightly adjusted version of your code:
import fs from "node:fs";
const merged = fs.readFileSync("/Users/emfive/Downloads/mergedData.dat", "utf-8");
const decoded = Buffer.from(merged, "base64");
console.log("original: " + merged.length);
console.log("decoded: " + decoded.length);
fs.writeFileSync("foo.mp4", decoded);
It takes no time to run, reading the source and writing the decoded result in under a second. There's no need for streams or "chunked" operations.
If the code in the question is not working, then there's something about it that has not been shared. For example, when you read in the base64 content, you have to make sure you're reading a string (by adding "utf-8" to the readFileSync() method).
the issue may be that the decoded data is not complete, leading to a smaller file size than expected.
To ensure that the entire base64 string is decoded, you can try this:
let outputFileName = "myfile.mp4";
let mergedData = "BASE64 DATA GOES HERE";
let chunkSize = 1024;
let decodedData = Buffer.alloc(0);
for (let i = 0; i < mergedData.length; i += chunkSize) {
let chunk = mergedData.substr(i, chunkSize);
decodedData = Buffer.concat([decodedData, Buffer.from(chunk, "base64")]);
}
fs.writeFileSync(outputFileName, decodedData);