mirror of
https://github.com/Wessel/kirbe.git
synced 2026-07-19 14:54:02 +02:00
Upload main code
This commit is contained in:
47
extensions/static.js
Normal file
47
extensions/static.js
Normal file
@@ -0,0 +1,47 @@
|
||||
const fs = require( 'fs' );
|
||||
const url = require( 'url' );
|
||||
const { join, extname } = require( 'path' );
|
||||
|
||||
const mimes = JSON.parse( fs.readFileSync( join( __dirname, 'mimes.json' ) ) );
|
||||
|
||||
module.exports = ( baseDir, indexFile ) => {
|
||||
if (!baseDir) throw new Error('The argument "baseDir" is required for the extension "kirbe:static"');
|
||||
|
||||
indexFile = typeof indexFile === 'string' ? indexFile : 'index.html'
|
||||
return( req, res, next ) => {
|
||||
if( req.method !== 'GET' ) { next(); return; }
|
||||
|
||||
let requestedPath = req.parsedUrl.pathname.replace( /\/.\.\//g, '' );
|
||||
let requestedExt = extname( requestedPath );
|
||||
|
||||
const filePath = join( baseDir, requestedPath );
|
||||
|
||||
fs.stat( filePath, ( err, stats ) => {
|
||||
if( err ) { next(); return; }
|
||||
|
||||
if( stats.isFile() ) {
|
||||
stats.mtime.setMilliseconds( 0 );
|
||||
if ( stats.mtime <= new Date( req.headers[ 'if-modified-since' ] ) ) res.status( 304 ).end();
|
||||
else fs.createReadStream( filePath ).pipe( res.status( 200 ).coreRes );
|
||||
} else {
|
||||
if ( req.parsedUrl.pathname.charAt( req.parsedUrl.pathname.length -1 ) !== '/' ) {
|
||||
res.status(302).header({ 'Location': `${req.parsedUrl.pathname}/` }).end();
|
||||
return;
|
||||
}
|
||||
|
||||
requestedPath = join( filePath, indexFile );
|
||||
requestedExt = extname( requestedPath );
|
||||
|
||||
fs.readFile( requestedPath, ( err, data ) => {
|
||||
if (err) next();
|
||||
else {
|
||||
res.body( data ).status(200).header({
|
||||
'Content-Type': ( mimes.hasOwnProperty( requestedExt ) ? mimes[ requestedExt ] : 'application/octet-stream' ),
|
||||
'Last-Modified': stats.mtime.toString()
|
||||
}).end();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user