Very basic request response web server in NodeJS

Problem

I am learning node JS and want to create a very basic single purpose web service that runs a windows command (to create a new user in ejabberd chat server) on the server where the client can pass in a specific argument to the command (using ajax I imagine).

I’ve been using the basic ‘createServer’ tutorial as a template:

var sys = require('util')
var http = require('http');
var exec = require('child_process').exec;

var path = '"C:\\Program Files\\ejabberd-2.1.8\\bin\\ejabberdctl"';

http.createServer(function (req, res) {

var cmd = path + ' register nodeuser ejabberhost xxxxxx';

var child = exec(cmd, function (error, stdout, stderr) {

var msg;

if (error !== null) {
msg = 'Error : ' + error;
}
else{
msg = stdout;
}
// this will prob be JSON
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(msg);
});

}).listen(1337, "localhost");

console.log('Server running at http://localhost:1337/');

In the above code ‘nodeuser’ needs to be replaced with an argument passed from the client in the request, using ajax. How could I tweak this code to achieve that?

Problem courtesy of: Sean Thoman

Solution

Input sanitation issues aside, here’s how you would do this:

http.createServer(function (req, res) {
var dataInput;
if (req.url === '/foo') {
req.on('data', function (chunk) {
dataInput = chunk.toString();
})
}
if (dataInput !== undefined) {
var cmd = path + ' register nodeuser ejabberhost ' + dataInput;
}

...

Solution courtesy of: fourk

View additional discussion.