This is my directory structure:
/Users/titi/myproject/app/server/
....app.js
..../public
......../css
......../js
......../view
............index.html
............about.html
And my app.js file:
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile('/Users/Titi/myproject/app/server/public/view/index.html');
});
app.get('/about', function (req, res) {
res.sendFile('/Users/Titi/myproject/app/server/public/view/about.html');
});
app.listen(2000, function () {
console.log('Example app listening on port 2000!');
});
It works perfectly.
But I would like to know if there is a way to not have to write the whole path (/Users/Titi/myproject/app/server/public/view/about.html).
Is it possible to simplify?
You could specify a root
path in the sendFile()
options:
var viewOpts = { root: '/Users/Titi/myproject/app/server/public/view' };
app.get('/', function (req, res) {
res.sendFile('index.html', viewOpts);
});
Or you could use the built-in path
to make the absolute path for you:
var path = require('path');
// Assuming this script is inside the `server` portion of the path
app.get('/', function (req, res) {
res.sendFile(path.resolve('public/view/index.html'));
});