Reputation: 3131
I am developing an Express web application with Node JS on Google App Engine Flexible environment (Managed VMs). Basically I only have one static HTML page that I need to serve since everything is loaded dynamically in Angular JS.
While reading Express best practices I noticed that they discourage the use of res.sendFile which is exactly what I've been doing in development.
Since I am switching to production I'd like to use static-serve as suggested but I couldn't find any documentation that explains how to simulate res.sendFile.
Below you can find my current code.
var app = express();
app.use(express.static('www'));
app.get('/', oauth2.required, function (req, res) {
// ...
res.sendFile(path.join(__dirname + '/www/dashboard.html'));
// ...
});
Upvotes: 0
Views: 1017
Reputation: 4343
To serve a static file you can define a static folder content in expressJS
app.use('/public', express.static(path.join(__dirname, './public')));
which mean that every files in you public folder will be served as static content when you hit and url like mydomain.com/public/image.png
EDIT: if possible in your dev environment
You could use an nginx server to serve you static file and let you node.js server handle the dynamic content. It is usually the most optimized solution to reduce the requests on your node.js server that is slower to server static files than nginx for example.
An nginx configuration could be
root /home/myapp;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location /public/ {
alias /home/myapp/public/;
}
location / {
proxy_pass http://IPADRESSOFNODEJSSERVER:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
#try_files $uri $uri/ =404;
}
Every request with /public/ at the first part of the url will be handled by nginx and every other request will be proxied to you nodejs app at your IPADRESSOFNODEJSSERVER:NODEJSPORT
usually the IPADRESSOFNODEJSSERVER
is the localhost
The second option using NGNIX refers to the doc section
An even better option is to use a reverse proxy to serve static files; see Use a reverse proxy for more information.
http://expressjs.com/en/advanced/best-practice-performance.html#proxy
Upvotes: 1