Using express to send a modified file

I'd like to deliver a modified version of a file based on the URL route.

app.get('/file/:name/file.cfg', function (req, res) {
    res.send(<the file file.cfg piped through some sed command involving req.params.name>)
});

The point being, the response should not be of type text/html, it should be the same MIME type as normal (which may still be wrong, but at least it works).

I am aware of security issues with this approach. The question is about how to do this with express and node.js, I'll be sure to put in lots of code to sanitize input. Better yet, never hit the shell (easy enough to use JS rather than e.g. sed to do the transformation)

What's a normal filetype for you?

Set the mimetype using (docs):

app.get('/file/:name/file.cfg', function (req, res) {
    res.set('content-type', 'text/plain');
    res.send(<the file file.cfg piped through some sed command involving req.params.name>)
});

If you want to detect the file's mime type use node-mime


To send a file from disk use res.sendfile which sets the mimetype based on the extension

res.sendfile(path, [options], [fn]])

Transfer the file at the given path.

Automatically defaults the Content-Type response header field based on the filename's extension. The callback fn(err) is invoked when the transfer is complete or when an error occurs.

app.get('/file/:name/file.cfg', function (req, res) {
  var path = './storage/' + req.params.name + '.cfg';
  if (!fs.existsSync(path)) res.status(404).send('Not found');
  else res.sendfile(path);
});

You can also force the browser to download the file with res.download. express has much more to offer, have a look at the docs.

I believe the answer is something along these lines:

app.get('/file/:name/file.cfg', function (req, res) {
    fs.readFile('../dir/file.cfg', function(err, data) {
        if (err) {
            res.send(404);
        else {
            res.contentType('text/cfg'); // Or some other more appropriate method
            transform(data); // use imagination please
            res.send(data)
        }
    });
});

The cfg file I happen to be working with is (this is dump of node repl):

> express.static.mime.lookup("../kickstart/ks.cfg")
'application/octet-stream'
>

Quite the generic option, I'll say. Anaconda would probably appreciate it.