Skip to content

Instantly share code, notes, and snippets.

@lukekarrys
Last active May 1, 2021 03:26
Show Gist options
  • Save lukekarrys/9ecd1619ca0542e2c43abdaa33309550 to your computer and use it in GitHub Desktop.
Save lukekarrys/9ecd1619ca0542e2c43abdaa33309550 to your computer and use it in GitHub Desktop.
node download file server
const http = require("http");
const fs = require("fs");
const serve = (res, data, headers) => {
res.writeHead(200, headers);
res.end(data);
};
const randomName = () => Math.random().toString().slice(2);
const PATHS = {
download: "downloadfile",
open: "openfile",
};
const requestListener = function (req, res) {
if (req.url === "/") {
serve(
res,
`
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>title</title></head>
<body>
<a href="${PATHS.download}">Download File</a>
<a href="${PATHS.open}">Get File</a>
</body></html>
`
);
} else if (req.url === `/${PATHS.download}`) {
serve(res, "TEXTFILE", {
"Content-Disposition": `attachment; filename="${randomName()}.txt"`,
});
} else if (req.url === `/${PATHS.open}`) {
serve(res, "TEXTFILE");
}
};
const server = http.createServer(requestListener);
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment