I often create little bash/C/obscure other language/… programs that I like to share, However,these programs are often not made to be hooked up to the Internet. So I use this script to create a quick web interface for my program and put it up on some cheap server.

The basic script is this:

var sys = require("util"),
  exec = require("child_process").exec,
  http = require("http"),
  url = require("url");

// argument to node is the portnumber
var port = parseInt(process.argv[2], 10) || 8888;

//Simple function to show error messages
function showError(response, code, error) {
  response.writeHead(code, { "Content-Type": "text/plain" });
  response.write(error);
  response.end();
}

http
  .createServer(function (request, response) {
    //Get information of the request
    var uri = url.parse(request.url).pathname;

    // Check the input
    // Be as strict as possible, Exposing a system call is dangerous
    // you don't want anyone to execute
    // rm -rf / or something like that...

    var arguments = ...;

    exec("./myFancyProgram " + arguments, function (error, stdout, stderr) {
      if (error !== null) {
        //Something went wrong -> write it to the server logs
        console.log("exec error: " + error);

        //Tell the user something went wrong
        showError(response, 500, "Something went wrong...");
        return;
      } else {
        response.writeHead(200, { "Content-Type": "text/plain" }); //or text/html
        response.write("stdout: \n" + stdout);
        response.write("stderr: \n" + stderr);
        response.end();
      }
    });
  })
  .listen(port);

console.log(
  "Program server running at\n => http://localhost:" +
    port +
    "/\nCTRL + C to shutdown"
);

You can use url.parse(request.url) to get the parts of the URL. The pathname gives the path without query string, splitting this on / will give you an array of parameters. The NodeJS URL documentation gives an overview of the parts of the request URL that you can easily retrieve.

Tough the snippet states it, I would like to stress that you should validate the input strictly. If you don’t your server wont be yours for long…