Static File Serving
Novaxjs2 provides built-in static file serving with automatic MIME type detection, intelligent minification, and efficient file handling.
Basic Usage
// Serve files from 'public' directory
app.serveStatic('public');
// Files will be available at:
// public/style.css -> /style.css
// public/images/logo.png -> /images/logo.png
// public/js/app.js -> /js/app.js
Custom Directory
// Serve from 'assets' directory instead
app.serveStatic('assets');
// Serve from multiple directories
app.serveStatic('public');
app.serveStatic('uploads'); // Files will be available under /uploads path
MIME Types and Content Detection
Novaxjs2 automatically detects file types from extensions using a comprehensive MIME type database with 80+ supported types:
// Automatic content type detection for:
// CSS, JavaScript, Images, Videos, Audio, Documents, Fonts, etc.
// Example detected types:
// .css -> text/css
// .js -> application/javascript
// .html -> text/html
// .png -> image/png
// .jpg -> image/jpeg
// .pdf -> application/pdf
// .json -> application/json
// .xml -> application/xml
// .zip -> application/zip
Automatic Minification
Static files are automatically minified when the minifier is enabled:
// Enable minification (enabled by default)
app.init({ minifier: true });
// CSS and JavaScript files are minified automatically
// HTML files are minified with intelligent content preservation
// Binary files (images, videos, etc.) are served without modification
Complete Static File Example
const Nova = require('novaxjs2');
const app = new Nova();
// Serve static files from public directory
app.serveStatic('public');
// Custom route that uses static assets
app.get('/', (req, res) => {
return `
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h1>Welcome</h1>
<img src="/images/logo.png" alt="Logo">
<script src="/js/app.js"></script>
</body>
</html>
`;
});
// API route that serves JSON data
app.get('/api/data', (req, res) => {
return res.json({ message: 'API response' });
});
app.at(3000, () => console.log('Server running on port 3000'));
Directory Structure Example
project/
├── public/
│ ├── css/
│ │ └── style.css
│ ├── js/
│ │ └── app.js
│ ├── images/
│ │ └── logo.png
│ └── favicon.ico
├── uploads/
│ └── user-uploads/
├── views/
│ └── home.html
└── index.js
Advanced Configuration
// Initialize with custom options
app.init({
staticPath: 'assets', // Custom static directory
minifier: true, // Enable minification
fileConfig: { // File upload configuration
maxSize: 10,
allowedTypes: ['image/*'],
maxFiles: 5
}
});
// You can also serve static files from multiple directories
app.serveStatic('public');
app.serveStatic('node_modules/bootstrap/dist'); // Bootstrap assets
Security Considerations
- Static files are served with proper content-type headers
- Directory traversal attacks are prevented
- Large files are streamed efficiently
- Binary files are handled correctly without encoding issues