Express 4: Serve Static Files
Run npm install express
to install Express.
We can use express.static
to load a directory of files we want to serve.
app.use(express.static('static-files-folder'))
will serve everything in the static-files-folder
folder at the root of our IP or domain: localhost:8080/FILE_NAME
const express = require('express');
const http = require('http');
// Environment variables
const PORT = 8080;
// Set up Express application
const app = express();
app.use(express.static('static-files'));
// Create HTTP server
http.createServer(app).listen(PORT, () => {
console.log(`listening on ${PORT}...`);
});
If we wish to load our static files with a path prefix, we can add it to app.use
like so: app.use('/public', express.static('static-files'))
this will load the files at localhost:8080/public/FILE_NAME
.