Created
January 24, 2025 00:14
-
-
Save Badbird5907/ff24a6d8f20abc82b06a203de278055a to your computer and use it in GitHub Desktop.
Datauri QR Code Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as fs from 'fs'; | |
import * as path from 'path'; | |
import * as zlib from 'zlib'; | |
import * as QRCode from 'qrcode'; | |
const mode = process.argv[2]; | |
const filePath = process.argv[3]; | |
if (!filePath) { | |
console.error("Please provide a path to the html file as the third argument."); | |
process.exit(1); | |
} | |
if (mode !== "gzip" && mode !== "urlencode" && mode !== "base64") { | |
console.error("Invalid mode. Please use 'gzip', 'urlencode', or 'base64'."); | |
process.exit(1); | |
} | |
console.log(`Mode: ${mode}`); | |
const generateDataUri = (htmlContent: string) => { | |
if (mode === "gzip") { | |
const gzippedContent = zlib.gzipSync(htmlContent); | |
const base64Gzip = gzippedContent.toString('base64'); | |
const decompressionScript = `<script>let a="${base64Gzip}",b=atob(a),c=new Uint8Array(b.length);for(let e=0;e<b.length;e++)c[e]=b.charCodeAt(e);let d=new Response(c).body.pipeThrough(new DecompressionStream("gzip"));new Response(d).text().then((e=>{document.open(),document.write(e),document.close()}));</script>`; | |
const dataUri = `data:text/html;utf8,${encodeURIComponent(decompressionScript)}`; | |
return dataUri; | |
} else if (mode === "urlencode") { | |
const urlencoded = encodeURIComponent(htmlContent); | |
const dataUri = `data:text/html;utf8,${urlencoded}`; | |
return dataUri; | |
} | |
// return base64 | |
const base64 = Buffer.from(htmlContent).toString('base64'); | |
const dataUri = `data:text/html;base64,${base64}`; | |
return dataUri; | |
} | |
async function generateQr(fp: string) { | |
const filePath = path.resolve(fp); | |
try { | |
const outDir = path.resolve('out'); | |
if (!fs.existsSync(outDir)) { | |
fs.mkdirSync(outDir); | |
} | |
const htmlContent = fs.readFileSync(filePath, 'utf-8'); | |
const dataUri = generateDataUri(htmlContent); | |
console.log(`Data URI size (${mode}): ${dataUri.length} bytes`); | |
fs.writeFileSync(path.join(outDir, 'dataUri.txt'), dataUri); | |
const qrCodePath = path.join(outDir, 'qr.png'); | |
await QRCode.toFile(qrCodePath, dataUri, { | |
width: 1000, | |
errorCorrectionLevel: 'L', | |
margin: 1, | |
version: 40, | |
}); | |
console.log(`QR Code saved as ${qrCodePath}`); | |
} catch (error) { | |
console.error('Error:', error.message); | |
} | |
} | |
generateQr(filePath); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment