使用快递发送修改后的文件

我想根据URL路由提供一个文件的修改版本。

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

重点是,响应不应该是types的text/html ,它应该是相同的MIMEtypes正常(这可能仍然是错误的,但至less它的作品)。

我知道这种方法的安全问题。 问题是关于如何使用express和node.js来做到这一点,我一定会放入很多代码来清理input。 更好的是,从来没有打过shell(容易使用JS而不是sed来完成转换)

我相信答案是这样的:

 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 value transform(data); // use imagination please, replace with custom code res.send(data) } }); }); 

我碰巧正在处理的cfg文件是(这是节点repl的转储):

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

相当普遍的select,我会说。 python可能会感激它。

什么是你的正常文件types?

使用( docs )设置mimetype:

 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>) }); 

如果要检测文件的MIMEtypes,请使用node-mime


要从磁盘发送文件,请使用res.sendfile ,它根据扩展名设置mimetype

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

在给定的path上传输文件。

基于文件名的扩展名自动默认Content-Type响应头字段。 当传输完成或发生错误时,调用fn(err)。

 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); }); 

您也可以强制浏览器使用res.download下载文件。 快递有更多的提供,看看文件。