Sending whole folder content to client with express - javascript

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 !

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 your html5game directory into some common directory, e.g. called html and put it where you have your Node.js program. An example directory layout would be:
/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)
Now, in your Node program you can use something like this:
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+'/');
});
This will serve all of your files (including index.html) on addresses like:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
Of course you still need to make sure that you refer to your assets in your index.html file correctly, for example with:
<script src="/html5game/xxx.js"></script>
in the case of the example layout above.
The top level directory with your static assets (where you have your index.html) is usually called static, public or html but you can call it whatever you like, as long as you use the correct path in your call to express.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:
app.use(express.static(htmlPath));
to this:
app.use('/game', express.static(htmlPath));
Then instead of those URLs:
http://localhost:3000/ (your index.html)
http://localhost:3000/html5game/xxx.js (your assets)
those URLs will be available instead:
http://localhost:3000/game/ (your index.html)
http://localhost:3000/game/html5game/xxx.js (your assets)
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:
https://github.com/rsp/node-express-static-example
See also some other answers where I talk about it in more detail:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
onload js call not working with node
Loading partials fails on the server JS
Node JS not serving the static image

The workaround for this is to compress the directory using the archiver library and uncompress it on the front end.

Related

Express.js server not working all of a sudden - Cannot GET /

My extremely simple express server using node.js suddenly stopped working. It was working fine (only testing it on my local machine for now), then I tried using browserify (which didn't work and I ended up deleting it) and when I went back to the site I was getting a Cannot GET / error.
I've tried uninstalling browserify, re-installing it, uninstalling and re-installing the two npm packages I'm using, even deleting all of my folders and starting from scratch (just pasting in the code on a couple of files). No matter what I still get the same error and I have no idea why. If I open index.html it still opens perfectly, while when I run my server (index.js) it doesn't throw any errors and seems to be listening as it's supposed to.
The server at the moment:
var path = require('path');
var express = require('express');
var app = express();
var dir = path.join(__dirname, 'public');
app.use(express.static(dir));
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
My files are currently structured like this:
public
assets (just has some images)
node_modules
index.html
index.js
package-lock.json
styles.css
Your index.html file should be in public folder and then it will work. At the moment, you have set the static path to public folder which doesn't contain any file.
Since your server's path is /public/index.js, path.join(__dirname, 'public') is resolving to /Users/.../your_directory/public/public. Express cannot find such a directory, so it proceeds down its pipeline. Since you did not define a GET / route, Express throws the error.
I would recommend removing your server file from /public.
Here's what your new directory tree would look like:
my_directory
node_modules
public
assets
index.html
styles.css
server
server.js (index.js in your case)
After you set up your directory tree as such, you can change the following:
var dir = path.join(__dirname, 'public');
// becomes
var dir = path.join(__dirname, '..', 'public');
// The '..' is used to move one directory level up.
Then, you should be able to see index.html when going to http://localhost:3000.

Locating files using Node.js and Socket.io

I am having trouble with local includes on the client side using Node.js and Socket.io. This may be to my PHP/Apache mindset I have had for file requests for most of my life.
On my server, I load the page likewise:
var express = require("express");
var app = express();
var path = require("path");
var server = require("http").createServer(app);
var io = require("socket.io")(server);
var mysql = require("mysql");
var port = process.env.PORT;
var ip = process.env.IP;
app.use(express.static(__dirname + "/client"));
//start opening socket connection handlers ...
And my files are organized likewise:
games
libraries
bigInt
threejs
etc...
version_1
client
index.html
index.js
index.css
server.js
database.sql
version_2
version_3
etc...
Depending which version I want to run, I open that version's directory and run its server.js file. The line redirects the client to /client/index.html with the line app.use(express.static(__dirname + "/client")). But now only files that are in the client folder are reachable by <script></script> or <link> tags but not those libraries in the libraries folder that I use across versions.
How do I change my code to be able to access files inside the libraries folder from /version_x/client/index.html while still directing the client to proper html file?
Note: Due to this issue, I have been forced to use only libraries with supported CDNs for the past couple weeks I have been learning Node.js.
Add the following line right after var ip = process.env.IP;:
app.use('/libraries', express.static(path.join(__dirname, '..', 'libraries'));
What this does is adding a new route to your application server. All your files inside your /games/libraries folder are now accessible via /libraries.
How does it work? Your express router uses different middlewares based on the provided paths. This line tells the router, to use the static middleware and serve files from ../libraries when a HTTP Request for anything under /libraries comes in.
You can serve more folders with express.static
//Serve Client Folder
app.use(express.static(__dirname + "/client"));
//Server External Libraries Folder
app.use('/libs', express.static(__dirname + "/../libraries"));
//Ex: <script src="libs/threejs/threejs.js">
//Will load libraries/threejs/threejs.js

onload js call not working with node

I am starting to learn node.js, for now I am just trying to execute my old none node app with node. In this app, I have a html page with a body calling an onload js function. It's working just fine.
Now I have a a node app: app.js, simple as that:
var express = require ('express');
var app = express ();
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ketcher'));
app.use(express.static(__dirname +'/ChemAlive_JS'));
app.get('/', function(req, res) {
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/ChemAlive_Interface.html');
});
app.listen(8080);
And in the .html I still have:
<body onload="ketcher.init();">
but the function I want to load is not load at all anymore.
Any clue?
Thanks
You have not provided a lot of info in the question but from what you provide I can have few suggestions:
Suggestions
Instead of adding a lot of express.static uses:
app.use(express.static(__dirname + '/images'));
app.use(express.static(__dirname + '/CSS'));
app.use(express.static(__dirname + '/font'));
app.use(express.static(__dirname ));
app.use(express.static(__dirname +'/ketcher'));
app.use(express.static(__dirname +'/ChemAlive_JS'));
put those files (and directories) that you want to be served into one directory, e.g. called static, and use express.static once:
app.use(express.static(__dirname + '/static'));
or better yet, using the path module:
app.use(express.static(path.join(__dirname, 'static')));
you need to require the path module first with:
var path = require('path');
Now, instead of serving the single file for the '/' route with:
app.get('/', function(req, res) {
res.sendFile('/home/laetitia/Project/ChemAlive_Interface_Node/ChemAlive_Interface.html');
});
just put that file into the static directory as index.html so it will be served by the express.static middleware automatically.
Rationale
The way you have it configured currently, is that e.g. everyone can download your Node application - app.js with all of its configuration and even submodules etc.
Also, by using the express.static middleware many times I suspect that you are not sure how the files in those directories will be mapped to URLs.
Having a one place for static files makes it easy to verify whether any script tags have correct paths etc.
My guess
You don't provide enough info to be sure but my guess is that the JavaScript files for the main HTML file are not loaded correctly but you provide not enough info to be sure.
You can open the developer tools console in the browser and reload the page while the console is open and see for errors.
I suspect that the ketcher.init() method is being run but either the method, or the ketcher object is undefined, because some <script> tags failed to be loaded.
Example
The full example after following my suggestions would be much simpler:
var path = require('path');
var express = require ('express');
var app = express();
app.use(express.static(path.join(__dirname, 'static')));
app.listen(8080);
Maybe I would add some output to see what's going on:
var path = require('path');
var express = require ('express');
console.log('starting app.js');
var app = express();
app.use(express.static(path.join(__dirname, 'static')));
app.listen(8080, function () {
console.log('listening on http://localhost:8080/');
});
And now you will have all files that can be served to the browser in one place: in the static directory in this example.
Working app
You can see my example of a working Express application serving static files on GitHub:
https://github.com/rsp/node-express-static-example
In this example the directory for static files is called html but you can call it how you want, as long as it's consistent with how you use the express.static middleware.
You can start from this example project and just put your own files into the directory where express.static is told to look for files to serve.
You can also change the port number to match your needs.
More examples to do the same with and without Express, plus better explanation:
https://github.com/rsp/node-static-http-servers
More hints
The onload callback may not be fired if the page is waiting for some resources to load.
To see if your onload callback is firing you can change it to:
<body onload="alert('onload callback fired');">
Also the ketcher object may be not initialized or it may not have the init() method. After the page is loaded you can open the JavaScript Console and try running the method manually to see if it would work if it was fired:
ketcher.init();
You can also try commands like:
console.dir(ketcher.init);
console.dir(ketcher);
console.log(typeof ketcher.init);
console.log(typeof ketcher);
to see if the ketcher object contains what it should.
Even if the GET localhost:8080/ketcher.js gives a 200 OK status, it can still load some other resources that are not available or, as is very common with code that serve files with res.sendFile() (though unlikely in this case), it can serve HTML instead of JavaScript and result in a cryptic parse error on the < character - see this question for example:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 while acess static files in node server
Other related answers:
How to serve an image using nodejs
Failed to load resource from same directory when redirecting Javascript
Sending whole folder content to client with express
Loading partials fails on the server JS
Node JS not serving the static image

How do I include an external JavaScript file when serving an HTML file with a response object in expressjs?

My express app serves an HTML page from my disk upon the initial GET (i.e., if I hit "http://localhost:3000/" in the browser). Now I would like to access a JavaScript file which is in the same location in the disk as the HTML file. When I try to include it in 'index.html' by using
<script src="/myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="./myJavaScriptFile.js" type="text/javascript" ></script>
or
<script src="~/MyAbsolutePath/myJavaScriptFile.js" type="text/javascript"</script>
it doesn't work. The myJavaScriptFile.js file is never reached.
My express app looks like this:
var express = require('express')
var testMethod = require('./test')
var app = express()
app.use(bodyParser.urlencoded({ extended:false }));
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
app.get('/', function (req, res) {
console.log('In /');
res.sendFile(__dirname + '/index.html');
})
Express app is serving 'index.html' using the reference path '__dirname' + '/index.html' using res.sendFile function. (I am beginning to feel that this is a bad way of doing it. Please let me know if you think so too).
Also as we can see in the express app, an external JavaScript file called 'test' which is in the same location as 'index.html' and 'express.js' is being included without any issues. Could anyone please shed light on what's actually happening in the background? What exactly would be reference path for the JavaScript file that I can give in my 'index.html' if it is being served by express app? Thank you.
Serving files, such as images, CSS, JavaScript and other static files is accomplished with the help of a built-in middleware in Express - express.static.
Pass the name of the directory, which is to be marked as the location of static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do this:
app.use(express.static('public'));
Now, you will be able to load the files under the public directory:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
More Detail Here
Happy Helping!

Loading scripts in a Node app

This is my folder structure:
- getable_challenge
- node_modules
- stuff
- main.html
- main.js
- backend.js
- README.md
I want to load main.js from within main.html. Previously I had been accessing the page using the URL of file:///Users/adamzerner/code/getable_challenge/main.html, and a simple <script src="main.js"></script> allowed me to load the script.
But then I set up a Node server, at localhost:3000, and now it won't load the script. It's trying to load localhost:3000/main.js, which presumably is the wrong path. I'm not sure how to structure this... what should I do?
Server code (essentially)
var express = require('express');
var app = express();
app.listen(3000);
When you use the "file" protocol like that you aren't even using the web app to serve the script, you are directly accessing it on the local file system. That works fine when you are just running your app on your local machine but it completely breaks when you try to run it as a real app since the browser will have no idea where "file:///..." is, or even have permission to access it.
You need to put the client side scripts into a separate directory, usually named 'public', and then make your application aware of it. If you're using express you would do this:
app.use(express.static(__dirname + '/public'));
You want to put your statically served scripts ("public") into a separate directory so as to control access by your clients. If you just put them into the main directory and made the main directory accessible you could expose all your other files to public view, such as config files that sometimes contain passwords.
It also makes your structure much cleaner.
Try adding this line after var app
app.use(express.static(__dirname));
This should make your resources that are within your servers folder accessible. the var __dirname is the path to where your server is executed.

Categories