Last active
November 19, 2025 04:59
-
-
Save sffc/6d62c6f0518485347bda688c4a2f20a4 to your computer and use it in GitHub Desktop.
Demo of importing non-UTF-8 JSON with the ESM module loader
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
| // Mixed-encoding JSON example server | |
| // | |
| // Instructions: | |
| // | |
| // 1. Run node json_encoding_server.mjs | |
| // 2. Visit http://localhost:8080/home.html | |
| // 3. Browse the console errors | |
| import http from "http"; | |
| const PORT = 8080; | |
| const server = http.createServer((req, res) => { | |
| if (req.url === "/home.js") { | |
| res.writeHead(200, { "Content-Type": "text/javascript" }); | |
| res.write(` | |
| import utf8json from "./utf8" with { type: "json" }; | |
| import latin1json from "./latin1" with { type: "json" }; | |
| import utf16lejson from "./utf16le" with { type: "json" }; | |
| console.log(utf8json); | |
| console.log(latin1json); | |
| console.log(utf16lejson); | |
| `); | |
| res.end(); | |
| return; | |
| } | |
| if (req.url === "/home.html") { | |
| res.writeHead(200, { "Content-Type": "text/html" }); | |
| res.write(` | |
| <script type="module" src="./home.js"></script> | |
| `); | |
| res.end(); | |
| return; | |
| } | |
| if (req.url === "/favicon.ico") { | |
| res.writeHead(404); | |
| res.end(); | |
| return; | |
| } | |
| let encoding = req.url.substr(1); | |
| console.log("Encoding:", encoding); | |
| try { | |
| res.writeHead(200, { "Content-Type": `text/json; encoding=${encoding}` }); | |
| let message = "Héllo 🌐"; | |
| if (encoding.indexOf("utf") === -1) { | |
| // Non-Unicode encodings don't support emoji | |
| message = "Héllo <emoji>"; | |
| } | |
| res.write(`{"message":"${message}"}\n`, encoding); | |
| } catch(e) { | |
| console.log(e); | |
| } finally { | |
| res.end(); | |
| } | |
| }); | |
| server.listen(PORT, "localhost", () => { | |
| console.log(`Server running at http://localhost:${PORT}/`); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment