用express发送整个文件夹内容给客户端
我做了一个html5游戏(使用GameMaker),它由一个index.html和一个包含游戏依赖关系的文件夹“html5game”组成 – javascript代码和资源。 问题是资源是相当多和多样的(声音,精灵等)和客户需要他们都玩。
我正在寻找一种方法来发送它们,而不是专门命名它们。
我试过了glob模块:
var glob = require( 'glob' ); var files = glob.sync( './html5game/**' ).forEach( function( file ) { require( path.resolve( file ) ); });
但我无法想出一个方法来发送文件使用res.sendFile()一旦我这样做。
我试过了
var express = require('express'); var app = express(); [...] app.get('/aeronavale/jeu', function(req, res){ res.sendFile(__dirname + '/aeronavale/index.html'); res.sendFile(files) }); [...] app.listen(3000, function(){ console.log('app started on port 3000, yeah !') })
但它给了我错误:
TypeError: path argument is required to res.sendFile
如果你有其他解决scheme,我也有兴趣。 感谢您的回答!
您将无法使用res.sendFile
发送多个文件。 你可以在这里做的最直接的事情是这样的:
把你的index.html
文件和你的html5game
目录放到一个公共的目录中,比如叫做html
并把它放在你有Node.js程序的地方。 示例目录布局将是:
/home/you/yourapp: - app.js (your node program) - package.json (your package.json etc) - html (a new directory) - index.html (your main html to serve) - html5game (the directory with other files) - (other files)
现在,在你的Node程序中,你可以使用这样的东西:
var path = require('path'); var express = require('express'); var app = express(); var htmlPath = path.join(__dirname, 'html'); app.use(express.static(htmlPath)); var server = app.listen(3000, function () { var host = 'localhost'; var port = server.address().port; console.log('listening on http://'+host+':'+port+'/'); });
这将为您的所有文件(包括index.html
)提供如下地址:
- http:// localhost:3000 / (你的
index.html
) - http:// localhost:3000 / html5game / xxx.js (您的资产)
当然,您仍然需要确保在index.html
文件中正确引用您的资产,例如:
<script src="/html5game/xxx.js"></script>
在上面的示例布局的情况下。
静态资产的顶层目录(你有你的index.html
)通常被称为static
, public
或者html
但是你可以随便调用它,只要你在你的调用中使用正确的pathexpress.static()
。
如果你想让你的游戏在根path以外的path上可用,那么你可以指定它为app.use
。 例如,如果你改变这个:
app.use(express.static(htmlPath));
对此:
app.use('/game', express.static(htmlPath));
然后,而不是这些url:
- http:// localhost:3000 / (你的
index.html
) - http:// localhost:3000 / html5game / xxx.js (您的资产)
这些url将可用:
- http:// localhost:3000 / game / (你的
index.html
) - http:// localhost:3000 / game / html5game / xxx.js (您的资产)
这里有很多问题都是关于使用Express来提供静态文件的,所以我做了一个工作的例子,并把它发布到GitHub上,这样人们就可以有一个工作的起点,并从那里开始:
另请参阅我在其中详细讨论的其他答案:
- 如何使用nodejs提供图像
- redirectJavascript时无法从同一目录加载资源
- onload js调用不与节点一起工作
- 在服务器JS上加载partials失败
- 节点JS不提供静态图像