Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Last active December 2, 2022 02:27
Show Gist options
  • Save mayankchoubey/2a9ec8bfa8c75208aa8711a55b747fda to your computer and use it in GitHub Desktop.
Save mayankchoubey/2a9ec8bfa8c75208aa8711a55b747fda to your computer and use it in GitHub Desktop.
Deno vs Node: Multipart/form-data with fields and files
import {readerFromStreamReader, copy} from "https://deno.land/std/streams/mod.ts";
const basePath=Deno.env.get('TMPDIR');
const listener = Deno.listen({ port: 3000 });
for await(const conn of listener)
handleNewConnection(conn);
async function handleNewConnection(conn: Deno.Conn) {
for await(const { request, respondWith } of Deno.serveHttp(conn)) {
const reqBody=await request.formData();
let totalFields=0, totalFiles=0, totalReceivedFileSize=0;
for(const e of reqBody.entries())
if(e[1] instanceof File) {
totalFiles++;
totalReceivedFileSize+=e[1].size;
await copy(readerFromStreamReader(e[1].stream().getReader()),
await Deno.open(basePath+`upload_${crypto.randomUUID()}`, {create: true, write: true}));
} else
totalFields++;
respondWith(new Response(JSON.stringify({totalFields, totalFiles, totalReceivedFileSize}), {
headers: { 'content-type': 'application/json'}
}));
}
}
const http = require("http");
const formidable = require("formidable");
const server = http.createServer(function (request, response) {
const form = new formidable.IncomingForm({ multiples: true });
form.parse(request, (err, fields, files) => {
response.writeHead(200, { "Content-Type": "application/json" });
let totalReceivedFileSize=0;
for(const f in files)
totalReceivedFileSize+=files[f].size;
response.end(JSON.stringify({
totalFields: Object.keys(fields).length,
totalFiles: Object.keys(files).length,
totalReceivedFileSize
}));
});
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment