I made an html5 game (using GameMaker), which is constituted of an index.html and a folder "html5game" that contains the dependencies of the game - the javascript code and the resources. The problem is the resources are quite numerous and diverse (sounds, sprites, etc.) and The client needs them all to play.
I am looking for a way to send them all without naming them specifically.
I tried the glob module :
var glob = require( 'glob' );
var files = glob.sync( './html5game/**' ).forEach( function( file ) {
require( path.resolve( file ) );
});
but I can't figure a way to send the files using res.sendFile() once I did that.
I tried
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 !')
})
but it gives me the error :
TypeError: path argument is required to res.sendFile
If you have an other solution, I a also interested. Thanks for your answers !
The workaround for this is to compress the directory using the archiver library and uncompress it on the front end.
You will not be able to send multiple file like that with
res.sendFile
. The most straightforward thing that you can do here would be this:Put your
index.html
file and yourhtml5game
directory into some common directory, e.g. calledhtml
and put it where you have your Node.js program. An example directory layout would be:Now, in your Node program you can use something like this:
This will serve all of your files (including
index.html
) on addresses like:index.html
)Of course you still need to make sure that you refer to your assets in your
index.html
file correctly, for example with:in the case of the example layout above.
The top level directory with your static assets (where you have your
index.html
) is usually calledstatic
,public
orhtml
but you can call it whatever you like, as long as you use the correct path in your call toexpress.static()
.If you want to have your game available in some path other than the root path then you can specify it to
app.use
. For example if you change this:to this:
Then instead of those URLs:
index.html
)those URLs will be available instead:
index.html
)A lot of questions here are related to serving static files with Express so I made a working example and posted it on GitHub so that people could have a working starting point and go from there:
See also some other answers where I talk about it in more detail: