const http = require('http');
const fs = require('fs').promises;
const routes = {
'/': (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
hx-download demo
hx-swap="download" demo
`);
},
'/htmx.js': async (req, res) => {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(await fs.readFile('src/htmx.js'));
},
'/ext/hx-download.js': async (req, res) => {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(await fs.readFile('src/ext/hx-download.js'));
},
// Small file — downloads instantly
'/small-file': (req, res) => {
let body = 'Hello from hx-download!\n';
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Length': Buffer.byteLength(body),
'Content-Disposition': 'attachment; filename="hello.txt"'
});
res.end(body);
},
// Large file — streams slowly so you can see the progress bar
'/large-file': (req, res) => {
let chunkSize = 16 * 1024; // 16 KB chunks
let totalChunks = 32; // 512 KB total
let total = chunkSize * totalChunks;
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': total,
'Content-Disposition': 'attachment; filename="test-data.bin"'
});
let sent = 0;
let interval = setInterval(() => {
let chunk = Buffer.alloc(chunkSize, 0x42); // fill with 'B'
res.write(chunk);
sent += chunkSize;
if (sent >= total) {
clearInterval(interval);
res.end();
}
}, 100);
req.on('close', () => clearInterval(interval));
}
};
http.createServer(async (req, res) => {
let pathname = new URL(req.url, 'http://localhost').pathname;
let handler = routes[pathname];
if (handler) {
try { await handler(req, res); }
catch (e) { if (!res.headersSent) { res.writeHead(500); res.end('Error'); } }
} else {
res.writeHead(404); res.end('Not Found');
}
}).listen(3001, () => console.log('http://localhost:3001'));