Usage with Bun
Bun is a toolkit for JavaScript and TypeScript development, allowing you to run, build, test, and debug a full-stack application.
For examples of projects, please refer to these resources: Bun or Bun TypeScript.
Initialization
1. Set up an entry point:
- JavaScript
- TypeScript
// 1. Import node-file-router
import { initFileRouter } from 'node-file-router';
// 2. Initialize the main request handler
const useFileRouter = await initFileRouter();
// 3. Start serving server and attach request handler to fetch
const server = Bun.serve({
port: 3123,
fetch: (req) => useFileRouter(req)
});
console.log(`Listening on http://localhost:${server.port}`);
// 1. Import node-file-router
import { initFileRouter } from 'node-file-router';
// 2. Initialize the main request handler
const useFileRouter = await initFileRouter();
// 3. Start serving server and attach request handler to fetch
const server = Bun.serve({
port: 3123,
fetch: async (req) => {
const res = await useFileRouter<Response>(req);
return res || new Response('No Response is provided', { status: 500 });
}
});
console.log(`Listening on http://localhost:${server.port}`);
2. Override the default 404 handler:
├── api/
│ └── _404.js
...
export default function NotFound() {
return new Response('404');
}
Handlers Implementation
Basic Handler
Bun operates with a Response
object that should be returned. Therefore, the API handlers look like the following:
├── api/
│ └── products.js
...
- JavaScript
- TypeScript
export default function ProductsRoute(req) {
return new Response('products');
}
export default function ProductsRoute(req: Request) {
return new Response('products');
}
Request and Response
├── api/users
│ └── [id].js
...
Since we have a response on return, the route params object is the second argument.
- JavaScript
- TypeScript
const db = {
13: { id: '13', name: 'Dan' }
}
export default {
async put(req, routeParams) {
db[routeParams.id] = await req.json();
return new Response(
JSON.stringify(db[routeParams.id]),
{ headers: { 'Content-Type': 'application/json' } }
);
}
}
interface User {
id: string,
name: string
}
interface Db {
[id: string]: User;
}
interface RouteParams {
id: string;
}
const db: Db = {
'13': { id: '13', name: 'Dan' }
}
function isUser(obj: unknown): obj is User {
return typeof obj === 'object' && obj !== null && 'id' in obj && 'name' in obj;
}
export default async function CreateOrUpdateUser(req: Request, routeParams: RouteParams) {
const maybeUser = await req.json();
if (!isUser(maybeUser)) {
return new Response('Invalid user', { status: 400 });
}
db[routeParams.id] = maybeUser;
return new Response(
JSON.stringify(db[routeParams.id]),
{ headers: { 'Content-Type': 'application/json' }}
);
}
Middlewares Implementation
For detailed information, please refer to the Middlewares Section. Generally, the interface can be described as follows:
- JavaScript
- TypeScript
export default function useMyMiddleware(req, next) {
// Code before
// ...
await next(); // <-- The router's code or next middleware (on nested levels)
// ...
// Code after
}
import type { NextFunction } from 'node-file-router';
export default function useMyMiddleware(req: Request, next: NextFunction) {
// Code before
// ...
await next(); // <-- The router's code or next middleware (on nested levels)
// ...
// Code after
}