Created
          October 12, 2021 03:30 
        
      - 
      
- 
        Save mayankchoubey/50a7edcfc4a3d2df00fd04bfd20fc3fe to your computer and use it in GitHub Desktop. 
    Deno vs Node: File server
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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 | |
| } | |
| })); | |
| } | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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