express static folder code example
Example 1: node express server static files
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
Example 2: express public folder
app.use(express.static('public'))
app.use(express.static('files'))
Example 3: express serve html
const path = require('path')
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const publicDirectoryPath = path.join(__dirname, '../public')
app.use(express.static(publicDirectoryPath))
app.listen(port, () => {
console.log(`Server is up on port ${port}!`)
})
Example 4: express img folder
app.use(express.static('public'))
Example 5: express serve static
app.use('/static', express.static(__dirname + '/public'));
Example 6: node js express static folder
// node js -> express -> basic example: static folder, 404 page
const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 5000;
const app = express();
function error404(req, res) {
res.status(404);
if (req.accepts('html')) {
res.sendFile(path.join(__dirname, 'public/errors/404.html'));
return;
}
if (req.accepts('json')) {
res.send({
status: 404,
error: 'Not found'
});
return;
}
res.type('txt').send('404 - Not found');
}
app
.use(express.static(path.join(__dirname, 'public')))
.use(error404)
.listen(PORT, () => console.log(`Listening on ${ PORT }`));