Skip to content

Instantly share code, notes, and snippets.

@alexjyong
Last active April 13, 2023 12:54
Show Gist options
  • Save alexjyong/0a9b274747e94dc93ceb8f5b7eb10bc5 to your computer and use it in GitHub Desktop.
Save alexjyong/0a9b274747e94dc93ceb8f5b7eb10bc5 to your computer and use it in GitHub Desktop.
Converts an html page with image links to an html page with base64 links in node.js
const fs = require('fs');
const request = require('request');
const { JSDOM } = require('jsdom');
const $ = require('jquery');
const pretty = require('pretty');
function convertImagesToBase64(inputFile, outputFile) {
fs.readFile(inputFile, 'utf8', (err, htmlContent) => {
if (err) throw err;
const dom = new JSDOM(htmlContent);
const $ = require('jquery')(dom.window);
const imgElements = $('img');
let pendingRequests = imgElements.length;
imgElements.each((index, img) => {
const src = img.getAttribute('src');
if (src.startsWith('http')) {
request.get({ url: src, encoding: null }, (err, response, body) => {
if (err) throw err;
const imgB64 = Buffer.from(body).toString('base64');
img.setAttribute('src', 'data:image/png;base64,' + imgB64);
pendingRequests--;
if (pendingRequests === 0) writeOutput();
});
} else {
fs.readFile(src, (err, imgData) => {
if (err) throw err;
const imgB64 = Buffer.from(imgData).toString('base64');
img.setAttribute('src', 'data:image/png;base64,' + imgB64);
pendingRequests--;
if (pendingRequests === 0) writeOutput();
});
}
});
function writeOutput() {
const prettyHtml = pretty(dom.serialize());
fs.writeFile(outputFile, prettyHtml, 'utf8', (err) => {
if (err) throw err;
console.log('Converted images to base64 and saved the output in', outputFile);
});
}
});
}
// Get command-line arguments
const args = process.argv.slice(2);
if (args.length !== 2) {
console.log('Usage: node convert_images_to_base64.js input_file output_file');
process.exit(1);
}
const inputFile = args[0];
const outputFile = args[1];
// Example usage:
convertImagesToBase64(inputFile, outputFile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment