Mai*_*tor 13 javascript node.js express
我正在使用一种相当丑陋的方法:
var app = require('express')(),
server = require('http').createServer(app),
fs = require('fs');
server.listen(80);
path = "/Users/my/path/";
var served_files = {};
["myfile1.html","myfile2.html","myfile3.html"].forEach(function(file){
served_files["/"+file] = fs.readFileSync(path+file,"utf8");
});
app.use(function(req,res){
if (served_files[req.path])
res.send(files[req.path]);
});
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?
num*_*407 18
Express有一个内置的中间件.它是connect的一部分,表达是建立在.中间件本身使用send.
// just add the middleware to your app stack via `use`
app.use(express.static(yourpath));
Run Code Online (Sandbox Code Playgroud)
回答你的评论,不,没有办法手动选择文件.虽然默认情况下中间件会忽略前缀的文件夹.,因此例如.hidden不会提供名为的文件夹.
要手动隐藏文件或文件夹,您可以static在请求到达之前插入自己的中间件以过滤掉路径.以下将阻止从名为的文件夹中提供任何文件hidden:
app.use(function(req, res, next) {
if (/\/hidden\/*/.test(req.path)) {
return res.send(404, "Not Found"); // or 403, etc
};
next();
});
app.use(express.static(__dirname+"/public"));
Run Code Online (Sandbox Code Playgroud)
Gol*_*den 12
如果您想在不使用Express的情况下获得解决方案(正如您明确要求的那样"简单"),请查看node-static模块.
它允许您像Express的适当中间件一样提供文件夹,但它也允许您只提供特定文件.
在最简单的情况下,它只是:
var http = require('http'),
static = require('node-static');
var folder = new(static.Server)('./foo');
http.createServer(function (req, res) {
req.addListener('end', function () {
folder.serve(req, res);
});
}).listen(3000);
Run Code Online (Sandbox Code Playgroud)
如果您需要一些示例,请查看GitHub项目页面,其中有几个.
PS:您甚至可以全局安装node-static并将其用作CLI工具,只需从您希望服务的文件夹中的shell运行它:
$ static
Run Code Online (Sandbox Code Playgroud)
而已 :-)!
PPS:关于您的原始示例,在这里使用带有流的管道更好,而不是以同步方式加载所有文件.
正如在这个问题的接受答案中所提到的,我建议使用http-server.
它可以通过命令行启动而无需任何配置
cd /path/to/directory
http-server
Run Code Online (Sandbox Code Playgroud)