Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Created October 12, 2021 03:30
Show Gist options
  • Save mayankchoubey/50a7edcfc4a3d2df00fd04bfd20fc3fe to your computer and use it in GitHub Desktop.
Save mayankchoubey/50a7edcfc4a3d2df00fd04bfd20fc3fe to your computer and use it in GitHub Desktop.
Deno vs Node: File server
import {readableStreamFromReader as toStream} from "https://deno.land/std/io/mod.ts";
const baseServePath='/Users/mayankc/Work/source/deno-vs-nodejs/testdata';
const listener = Deno.listen({ port: 3000 });
for await(const conn of listener)
handleNewConnection(conn);
async function handleNewConnection(conn: Deno.Conn) {
for await(const {request:req, respondWith:res} of Deno.serveHttp(conn)) {
const filePath=baseServePath+(new URL(req.url)).pathname;
const fileSize=(await Deno.stat(filePath)).size.toString();
res(new Response(toStream(await Deno.open(filePath)), {
headers: {
'content-type': 'text/javascript',
'content-length': fileSize
}
}));
}
}
const http = require("http");
const {stat}=require("fs").promises;
const fs = require("fs");
const baseServePath='/Users/mayankc/Work/source/deno-vs-nodejs/testdata';
const server = http.createServer(async (req, res) => {
const filePath=baseServePath+req.url;
const fileSize=(await stat(filePath)).size;
res.writeHead(200, {
'content-type': 'text/javascript',
'content-length': fileSize
});
fs.createReadStream(filePath).pipe(res);
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment