Skip to content

Instantly share code, notes, and snippets.

@Shrekie
Created March 15, 2022 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shrekie/f42224bb3556f2db663d36a26842f2de to your computer and use it in GitHub Desktop.
Save Shrekie/f42224bb3556f2db663d36a26842f2de to your computer and use it in GitHub Desktop.
Node server with images
<html>
<form id="image-form">
<input type="file" accept="image/*" name="image" />
<input type="submit" />
</form>
<div id="image-container"></div>
<script>
let data = { postMessage: "Hello Postworld" };
fetch("/api/posting", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then(async (res) => {
console.log(res);
console.log("response:", await res.json());
});
fetch("/api/getting", {
method: "GET",
headers: { "Content-Type": "application/json" },
}).then(async (res) => {
console.log(res);
console.log("response:", await res.json());
});
const imageForm = document.getElementById("image-form");
imageForm.onsubmit = async (e) => {
e.preventDefault();
let response = await fetch("/api/upload-image", {
method: "POST",
body: new FormData(imageForm),
});
const image = new Image(100, 100);
image.src = URL.createObjectURL(await response.blob());
document.getElementById("image-container").replaceChildren(image);
};
</script>
</html>
const http = require("http");
const fs = require("fs");
const path = require("path");
const busboy = require("busboy");
const PORT = process.env.PORT || 8080;
const getReqData = (req) => {
return new Promise((resolve, reject) => {
try {
let body = "";
req.on("data", (chunk) => {
body += chunk.toString();
});
req.on("end", () => {
resolve(body);
});
} catch (error) {
reject(error);
}
});
};
const serveFile = (filePath, res) => {
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
};
const server = http.createServer(async (req, res) => {
if (req.url === "/" && req.method === "GET") {
// APPLICATION.HTML
return serveFile(__dirname + "/application.html", res);
}
if (req.url === "/api/getting" && req.method === "GET") {
// GETTING
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ getMessage: "Hello Getworld" }));
}
if (req.url === "/api/posting" && req.method === "POST") {
// POSTING
const post_data = await getReqData(req);
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(post_data);
}
if (req.url === "/api/upload-image" && req.method === "POST") {
// UPLOAD IMAGE
const bus = busboy({ headers: req.headers });
bus.on("file", (name, file, info) => {
//const saveTo = path.join(os.tmpdir(), `busboy-upload-${random()}`);
const saveTo = path.join(__dirname, info.filename);
file.pipe(fs.createWriteStream(saveTo));
file.on("close", () => {
serveFile(saveTo, res);
});
});
return req.pipe(bus);
}
// NOT FOUND
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Route not found" }));
});
server.listen(PORT, () => {
console.log(`server started on port: ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment