Nodejs:如何为要下载的文件设置假path

在我的nodejs应用程序中,我有一个静态path“/ public”,它具有以下结构:

-public -images -js -posts -2017 -07 -08 -09 

正如你所看到的,我每年和每个月创build一个文件夹来存储文件。

现在,当我从视图链接文件,我可以看到path/posts/2017/09/file.txt ,我不想显示此

有没有办法设置一个虚假的path(也许有参数)为了隐藏我的文件夹结构?

对于像/files?date=2017-09这样的url,你可以这样做:

 const path = require('path'); // handle routes like this: /files?date=2017-09 app.get('/files', function(req, res) { let date = req.query.date; // if no date or if it contains illegal characters, then disallow it // this is important to prevent injection of weird paths and ../../ stuff if (!date || /[^\d-]/.test(date)) { return res.status(404).end(); } // I'm not sure what your root path is here, so replace /public with // whatever that is supposed to be let file = path.join('/public/posts', date.replace("-", path.sep)); res.sendFile(file, {dotfiles: "deny"}, function(err) { if (err) { res.status(404).end(); } }); });