Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Last active September 7, 2019 14:11
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 MarkTiedemann/74753888ac51601e56c735db7e447da4 to your computer and use it in GitHub Desktop.
Save MarkTiedemann/74753888ac51601e56c735db7e447da4 to your computer and use it in GitHub Desktop.
Poor Man's CGI with Node

Poor Man's CGI with Node

$ chmod +x script.sh
$ node server.js &
$ curl localhost -d hello
<!DOCTYPE html>
<pre>
POST / HTTP/1.1
Host: localhost
User-Agent: curl/7.54.0
Accept: */*
Content-Length: 5
Content-Type: application/x-www-form-urlencoded

hello
</pre>
#!/bin/bash
echo "<!DOCTYPE html>
<pre>
$method $url HTTP/$http_version_major.$http_version_minor
$(while read -r key val; do echo "$key: $val"; done <<< "$headers")
$(while read -r line; do echo "$line"; done)
</pre>"
const http = require("http")
const child_process = require("child_process")
http.createServer(function(req, res) {
let env = {
method: req.method,
url: req.url,
http_version_major: req.httpVersionMajor,
http_version_minor: req.httpVersionMinor,
headers: (function() {
let headers = []
for (let i = 0; i < req.rawHeaders.length; i++)
headers.push(req.rawHeaders[i] + " " + req.rawHeaders[++i])
return headers.join("\n")
})()
}
let child = child_process.spawn("./script.sh", { env })
req.pipe(child.stdin)
req.prependOnceListener("end", function() { child.stdin.write("\n") })
child.stdout.pipe(res)
}).listen(80)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment