Skip to content

Instantly share code, notes, and snippets.

@mLuby
Last active April 27, 2023 21:52
Show Gist options
  • Save mLuby/6cecf50649c543b6c89f3976cf203058 to your computer and use it in GitHub Desktop.
Save mLuby/6cecf50649c543b6c89f3976cf203058 to your computer and use it in GitHub Desktop.
NodeJS Server 1-liners

Submitted for your approval, a NodeJS solution in 123 chars. ⛳

r=require;r("http").createServer((i,o)=>r("stream").pipeline(r("fs").createReadStream(i.url.slice(1)),o,_=>_)).listen(8080)

Run it in bash to serve files relative to that directory, and also any file on your computer if given an absolute path. 😱

node -e 'r=require;r("http").createServer((i,o)=>r("stream").pipeline(r("fs").createReadStream(i.url.slice(1)),o,e=>console.log(i.url,e))).listen(8080)'

I prefer the 153-char version that logs out each file request and doesn't serve outside the command's directory. 🪵

r=require;r("http").createServer((i,o)=>r("stream").pipeline(r("fs").createReadStream(r("path").join(".",i.url)),o,e=>console.log(i.url,e))).listen(8080)

Here's that one-liner unobfuscated, deminimized, and explained. 🧑‍🏫

require("http").createServer((request, response) => {
  require("stream").pipeline( // Pipes from each stream to the next ending in a callback to handle errors
    require("fs").createReadStream( // Reads the file at the specified path.
      require("path").join(".", request.url) // Forces the file path to start with this directory,
    ),                                       // so no absolute paths or ../ing upward.
    response, // This is a writable stream so the file read stream pipes into the server response stream.
    (error, value) => { console.log(request.url, error); } // This callback handles the error & we use it
  )                                                        // here to log the filepath.
).listen(8080); // Actually starts the server listening on this port.
@mLuby
Copy link
Author

mLuby commented Mar 7, 2023

require("http").createServer((req, res)=>{ let body = ""; req.on("data", chunk => body += chunk); req.on("end", ()=>{ console.log(req.method, req.url, JSON.parse(body||"null")); res.end(); }); }).listen(8080);
curl localhost:8080/foo/bar                # GET /foo/bar null
curl localhost:8080/foo/bar -d '{"baz":4}' # POST /foo/bar { baz: 4 }

@mLuby
Copy link
Author

mLuby commented Apr 27, 2023

cat ~/Desktop/DaffyLintWarnings.json | \
node -e 'd=[];process.openStdin().on("data",c=>d.push(c)).on("end",()=>console.log(JSON.parse(d.join("")).sort((a,b)=>b.count-a.count).map(({ruleName,count})=>`${String(count).padStart(3)}:${ruleName}`).join(`\n`)))'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment