node.js / express:发送静态文件(如果存在)(node.js/express: Sending static files if they exist)

我想从文件夹中提供html文件(如果存在),否则回退到动态应用程序。

目前我用的是:

var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);

server.listen(4444);

app.use("/", express.static(__dirname + '/../WebContent/index.html'));
app.use("/styles", express.static(__dirname + '/../WebContent/styles'));
app.use("/script", express.static(__dirname + '/../WebContent/script'));

//here I would like to define a rule like this:
//app.use("*.html", express.static(__dirname + '/../WebContent/*html'));
 

我怎样才能做到这一点?

一些教程使用名为connect的模块。 如果这是我的问题最优雅的解决方案,我如何将连接集成到我当前的代码?

I want to serve html files from a folder if they exist, otherwise fallback to the dynamic app.

currently I use something like:

var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);

server.listen(4444);

app.use("/", express.static(__dirname + '/../WebContent/index.html'));
app.use("/styles", express.static(__dirname + '/../WebContent/styles'));
app.use("/script", express.static(__dirname + '/../WebContent/script'));

//here I would like to define a rule like this:
//app.use("*.html", express.static(__dirname + '/../WebContent/*html'));
 

How can I achieve this?

Some tutorials use a module called connect. If it's the most elegant solution to my problem, how can I integrate connect to my current code?

最满意答案

你不需要做任何特别的事情。

我假设WebContent文件夹在根目录中。

如果所有静态内容都与您所显示的基本文件夹相同,则不必多次指定。

app.use(express.static(__dirname + '/WebContent'));

如果你在WebContent文件夹中有一个名为file.html的文件,你现在可以通过url访问它,即localhost:4444 / file.html

You don't have to do anything special.

i'm assuming the WebContent folder is in the root.

And if all your static content are in the same base folder like you've shown, you don't have to specify it multiple times.

app.use(express.static(__dirname + '/WebContent'));

if you have a file called file.html in the WebContent folder you can now access it via the url i.e. localhost:4444/file.html

更多推荐