Skip to content

Commit

Permalink
feat: add static files path cli option
Browse files Browse the repository at this point in the history
  • Loading branch information
bbtgnn committed Dec 6, 2023
1 parent d10a7be commit 88306ce
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
6 changes: 6 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ program
}
})
)
.addOption(
new Option(
'--static-files-path <string>',
'specify the path under which static files will be served'
).default('/', 'root url')
)
.addOption(
new Option(
'-p, --port <number>',
Expand Down
14 changes: 8 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,16 @@ Dir.ready(async () => {

generateRoutes(app);

const { publicDirectory } = config;
const { publicDirectory, staticFilesPath } = config;
if (publicDirectory) {
app.get('/*', (res, req) => {
let file = path.join(publicDirectory, req.getUrl());
if (fs.existsSync(file)) {
const contentType = mime.getType(file) || 'application/octet-stream';
const route = path.join('/', staticFilesPath, '*');
app.get(route, (res, req) => {
const fileName = req.getUrl().split('/').at(-1)!;
const filePath = path.join(publicDirectory, fileName);
if (fs.existsSync(filePath)) {
const contentType = mime.getType(filePath) || 'application/octet-stream';
res.writeHeader('Content-Type', contentType);
res.end(fs.readFileSync(file));
res.end(fs.readFileSync(filePath));
} else {
res.writeStatus('404 Not Found').end('Not found');
}
Expand Down

0 comments on commit 88306ce

Please sign in to comment.