Reputation: 123
Hi guys I am working on this express aplication. In the top of my express file I wrote this line since all my static files are located in my working directory:
app.use(express.static(__dirname));
Now I want to send a file that exist in a parent folder of the current folder:
app.get('/test', function(req, res) {
res.sendFile("../../test.html");
});
It didn't work for me, Normally because all static files must exist in the directory defind above, Could I make an exception and make my code work?
Upvotes: 2
Views: 1209
Reputation: 12712
express.static
and res.sendFile
don't know anything about each other. They happen to share a lot of the same internals but aren't really related.
You can put test.html
wherever you want and then reference it using Node's built-in path
module. For example, if your file structure looks like this:
test.html
real-app/
├── app.js
├── node_modules/
└── package.json
Then you can send test.html
like this:
var path = require('path');
// ...
app.get('/test', function(req, res) {
var testHtmlPath = path.resolve(__dirname, '..', '..', 'test.html');
res.sendFile(testHtmlPath);
});
PS: I wouldn't recommend the way you're sending static files. Serving files from the same directory as your app code (which is what __dirname
means) can cause code disclosure, which hackers can use to exploit problems in your code. For example, if a hacker visited this URL:
They would be able to see app.js
, which has all of your application's code. You don't want to reveal that to a hacker! They could also navigate to routes like /secret-passwords.json
or other similar files.
Typically, static files are placed into a special directory, often called static
or public
. You can serve files from this directory like this:
var path = require('path');
// ...
var staticFilesPath = path.resolve(__dirname, 'public');
app.use(express.static(staticFilesPath));
In general, you should be pretty careful about sending files that live outside of your app's code.
Hope this helps!
Upvotes: 6