Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active September 27, 2024 10:59
Show Gist options
  • Select an option

  • Save james2doyle/a4cff8e12456318c71b1 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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

@james2doyle
Copy link
Copy Markdown
Author

@wenbolovesnz thanks for the heads up. Will update

@MeRahulAhire
Copy link
Copy Markdown

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