Created
April 28, 2021 10:05
-
-
Save Gregoor/52a12200f8be688f7168c7dfcff422c1 to your computer and use it in GitHub Desktop.
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
const fs = require("fs"); | |
const express = require("express"); | |
const cheerio = require("cheerio"); | |
const jsesc = require("jsesc"); | |
const BASE_HTML = ` | |
<!DOCTYPE html> | |
<html> | |
<body> | |
<div> | |
<button id="show-output">Show things!</button> | |
<div id="output"></div> | |
</div> | |
<script id="app-script" defer> | |
document.getElementById('show-output').addEventListener('click', () => { | |
document.getElementById('output').textContent = Object.keys(window.hydration); | |
}); | |
</script> | |
</body> | |
</html> | |
`; | |
const JSON_STRING = fs.readFileSync("1mb-test_json.json", "utf-8"); | |
const variants = [ | |
[ | |
"json", | |
($) => | |
$("#app-script").before( | |
`<script id="hydration" type="application/json">${JSON_STRING}</script>`, | |
'<script defer>window.hydration = JSON.parse(document.getElementById("hydration").textContent)</script>' | |
), | |
], | |
[ | |
"jsesc", | |
($) => | |
$("#app-script").before( | |
`<script>window.hydration = JSON.parse(${jsesc(JSON_STRING, { | |
json: true, | |
isScriptContext: true, | |
})})</script>` | |
), | |
], | |
].map(([name, mod]) => { | |
const $ = cheerio.load(BASE_HTML); | |
mod($); | |
return [name, $.html()]; | |
}); | |
const app = express(); | |
for (const [name, html] of variants) { | |
app.get("/" + name, (req, res) => { | |
res.send(html); | |
}); | |
} | |
const PORT = process.env.PORT || 1234; | |
app.listen(PORT, () => { | |
console.log("listening on", PORT); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment