Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active February 2, 2023 23:53
Show Gist options
  • Save james2doyle/a4cff8e12456318c71b1 to your computer and use it in GitHub Desktop.
Save james2doyle/a4cff8e12456318c71b1 to your computer and use it in GitHub Desktop.
base64 encode a file with node.js and auto-detect the mimetype.
// to run: node node-base64-encode.js file
const mime = require('mime'); // npm install mime
const path = require('path');
const fs = require('fs');
// path to the file we passed in
const filepath = path.resolve(process.argv[2]);
// get the mimetype
const filemime = mime.getType(filepath);
fs.readFile(filepath, {encoding: 'base64'}, (err, data) => {
if (err) {
throw err;
}
console.log(`data:${filemime};base64,${data}`);
});
@wenbolovesnz
Copy link

Thank you for the example.
As today, mime. lookup() function is renamed to getType()

@james2doyle
Copy link
Author

@wenbolovesnz thanks for the heads up. Will update

@MeRahulAhire
Copy link

Does it decodes the mimeType of Base64 string?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment