Skip to content

Instantly share code, notes, and snippets.

@yawboakye
Created December 14, 2022 17:02
Show Gist options
  • Save yawboakye/efd0f93b0780e4efa081eafdfe132b75 to your computer and use it in GitHub Desktop.
Save yawboakye/efd0f93b0780e4efa081eafdfe132b75 to your computer and use it in GitHub Desktop.
const assert = require("node:assert");
const http = require("node:http");
const path = require("node:path");
const fs = require("node:fs");
const os = require("node:os");
const host = "localhost";
const port = 5566;
function assembleFileContents(chunks, type) {
switch (type) {
case "octet": return Buffer.concat(chunks);
case "base64": return Buffer.from(Buffer.concat(chunks).toString(), "base64");
case "buffer": return Buffer.from(JSON.parse(Buffer.concat(chunks).toString()));
}
}
function receiveToFile(req, res, type) {
const contentLength = req.headers["content-length"];
const chunks = [];
const destinationPath = path.join(os.tmpdir(), `gh-woman-${type}-upload-${contentLength}.jpeg`);
req
.on("data", (chunk) => chunks.push(chunk))
.on("end", () =>
fs.writeFileSync(
destinationPath,
assembleFileContents(chunks, type)
)
);
res.write(destinationPath)
return res.end();
}
const server = http.createServer(function (req, res) {
switch (req.url) {
case "/binary": return receiveToFile(req, res, "octet");
case "/base64": return receiveToFile(req, res, "base64");
case "/buffer": return receiveToFile(req, res, "buffer");
default:
res.writeHead(404);
}
});
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment