javascript 使用 express 提供静态文件的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14576644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the simplest way to serve static files using express?
提问by MaiaVictor
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?
正确的做法是什么?
回答by numbers1311407
Express has a built in middleware for this. It's part of connect, which express is built on. The middleware itself uses send.
Express 有一个内置的中间件。它是connect的一部分,express 建立在它的基础上。中间件本身使用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.
回答您的评论,不,无法手动选择文件。尽管默认情况下中间件会忽略前缀.
为 的文件夹,因此例如.hidden
不会提供名为的文件夹。
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
:
要手动隐藏文件或文件夹,您可以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"));
回答by Golo Roden
If you want to have a solution without using Express (as you asked for "simple" explicitly), check out the node-staticmodule.
如果您想在不使用 Express 的情况下获得解决方案(正如您明确要求“简单”的那样),请查看node-static模块。
It allows you to serve a folder just like the appropriate middleware for Express, but it also allows you to serve only specific files.
它允许您像 Express 的适当中间件一样提供文件夹,但它也允许您仅提供特定文件。
In the simplest case it's just:
在最简单的情况下,它只是:
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);
If you need some examples, have a look at the GitHub project page, there are several of them.
如果您需要一些示例,请查看 GitHub 项目页面,其中有几个。
PS: You can even install node-static globally and use it as a CLI tool by just running it from the shell inside the folder you wish to serve:
PS:您甚至可以全局安装 node-static 并将其用作 CLI 工具,只需从您希望提供服务的文件夹内的 shell 中运行它:
$ static
That's it :-)!
而已 :-)!
PPS: Regarding your original example, it would be way better to use piping with streams here instead of loading all the files in a synchronous way.
PPS:关于您的原始示例,最好在此处使用带有流的管道,而不是以同步方式加载所有文件。
回答by kwcto
As mentioned in the accepted answer for this question, I'd recommend using http-server.
正如此问题的已接受答案中所述,我建议使用http-server。
It can be started via command line without any config
它可以通过命令行启动,无需任何配置
cd /path/to/directory
http-server
回答by ciny
Personally I prefer to server files from nginx (I also use it for gzip encoding, caching, SSL handling and load balancing) and node provides just the API. Maybe not the answer you're looking for but it offers interesting choices. Maybe you can have a look at this approach and find that you like it ;)
我个人更喜欢从 nginx 服务文件(我也将它用于 gzip 编码、缓存、SSL 处理和负载平衡),而 node 只提供 API。也许不是您正在寻找的答案,但它提供了有趣的选择。也许你可以看看这种方法并发现你喜欢它;)
回答by SuperNova
I did the below changes to AUTO-INCLUDE the files in the index html. So that when you add a file in the folder it will automatically be picked up from the folder, without you having to include the file in index.html
我对索引 html 中的文件进行了以下更改。这样当您在文件夹中添加文件时,它会自动从文件夹中提取,而无需将文件包含在 index.html 中
//// THIS WORKS FOR ME
///// in app.js or server.js
var app = express();
app.use("/", express.static(__dirname));
var fs = require("fs"),
function getFiles (dir, files_){
files_ = files_ || [];
var files = fs.readdirSync(dir);
for (var i in files){
var name = dir + '/' + files[i];
if (fs.statSync(name).isDirectory()){
getFiles(name, files_);
} else {
files_.push(name);
}
}
return files_;
}
//// send the files in js folder as variable/array
ejs = require('ejs');
res.render('index', {
'something':'something'...........
jsfiles: jsfiles,
});
///--------------------------------------------------
///////// in views/index.ejs --- the below code will list the files in index.ejs
<% for(var i=0; i < jsfiles.length; i++) { %>
<script src="<%= jsfiles[i] %>"></script>
<% } %>
回答by micnic
If you want a really simple way then I would like to show you my module (it is not only for static files) simpleS, install it using npm install simples
.
如果您想要一个非常简单的方法,那么我想向您展示我的模块(它不仅适用于静态文件)simpleS,请使用npm install simples
.
Put all your files in a folder, for example files
.
将所有文件放在一个文件夹中,例如files
.
Here is the magic:
这是魔法:
var simples = require('simples');
var server = simples(80);
server.serve('files');
/* if you want to catch the acces to a folder and to do something, try this:
server.serve('files', function (connection, files) {
// Your application logic
// For example show the files of the folder
});
*/
You don't need to care about the content type of the files, it will detect it automatically from file extension
您不需要关心文件的内容类型,它会从文件扩展名中自动检测