Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - What's the simplest way to serve static files using express?

I'm using a rather ugly approach:

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

What's the proper way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Express has a built in middleware for this. It's part of connect, which express is built on. The middleware itself uses send.

// just add the middleware to your app stack via `use`
app.use(express.static(yourpath));

In answer to your comment, no, there is no way to manually select files. Though by default the middleware will ignore folders prefixed with ., so for example a folder named .hidden would not be served.

To hide files or folders manually, you could insert your own middleware before static to filter out paths before the request reaches it. The following would prevent serving any files from folders named 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"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...