This article assumes that you know how to install a Node.js app on our platform and that you know how to run terminal commands such as npm within your app environment. Please familiarise yourself with the following help topics:
How to serve static files such as images, css and javascript is a common question that comes up when creating a Node.js app.
To do this you can use the express module.
To install express, enter your app environment and run:
npm install express
Then here is an example application startup file for serving static files. This is usually your app.js file but you may have chosen a different name when installing your app.
const express = require('express');
const path = require('path');
const app = express();
const router = express.Router();
// This serves files from the 'public' directory, relative to the router's base path
router.use(express.static(path.join(__dirname, 'public')));
router.get('/', (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
const message = 'It works from the router!\n';
const version = 'NodeJS ' + process.versions.node + '\n';
const response = [message, version].join('\n');
res.end(response);
});
// Tell the main app to use this router for all requests starting with "/static" or whatever route you prefer
app.use('static', router);
// Phusion Passenger will listen on the correct port
app.listen();
The above code creates an express router for handling static files, tells it to look for files in the 'public' directory and makes them available at the 'static' endpoint. So your static files are served from a url like /static/some-static-file.jpg