Serve static files using Bun.serve or Bao.js

Overview

serve-static-bun

NPM Version

Serve static files using Bun.serve or Bao.js.

Currently in beta. Aiming for similar features as expressjs/serve-static.

Install

This is a Bun module available through the npm registry. Installation is done using the bun install command:

bun install serve-static-bun

Usage

import serveStatic from "serve-static-bun";

serveStatic(root, options)

Create a new middleware function to serve files from within a given root directory. The file to serve will be determined by combining req.url with the provided root directory.

When a file is not found, it will send a 404 response. If a directory is accessed, but no index file is found, a 403 response will be sent.

When used in middleware mode, the 404 and 403 responses will not be sent and will instead return the context to Bao.js, so that other routes can continue.

By default, slashes are automatically collapsed in the path, and a trailing slash is added when the path is a directory. For example, if you have blog/example/index.html and access https://example.com//blog///example, it will redirect to https://example.com/blog/example/.

Options

index

By default this module will send "index.html" files in response to a request on a directory. To disable this, set it to false. To supply a new index, pass a string.

dirTrailingSlash

Redirect to trailing "/" when the pathname is a dir. Defaults to true.

collapseSlashes

Collapse all slashes in the pathname (//blog///test => /blog/test). Defaults to true.

stripFromPathname

Removes the first occurence of the specified string from the pathname. Defaults to false (disabled).

headers

Headers to add to the response. The "Content-Type" header cannot be overwritten. If you want to change the charset, use the charset option. If collapseSlashes or dirTrailingSlash is set, a "Location" header will be set.

fileEncoding

The encoding of the static files that will be served. Must be of BufferEncoding type. Defaults to utf8.

charset

The "Content-Type" HTTP header charset parameter. Defaults to utf-8.

middlewareMode

When set to "bao", it will return a Bao.js compatible handler function instead.

handleErrors (Middleware only)

If set to false, in the case of a 403 or 404 response, the unmodified context will be returned to Bao.js. Defaults to true.

Examples

Serve files with vanilla Bun.serve

import serveStatic from "serve-static-bun";

Bun.serve({ fetch: serveStatic("public") });

Serve files with Bao.js

import Bao from "baojs";
import serveStatic from "serve-static-bun";

const app = new Bao();

// *any can be anything
// We need to strip /assets from the pathname, because when the root gets combined with the pathname, it results in /assets/assets/file.js.
app.get("/assets/*any", serveStatic("assets", { middlewareMode: "bao", stripFromPathname: "/assets" }));

app.get("/", (ctx) => ctx.sendText("Hello Bao!"));

app.listen();

Serve only static files with Bao.js

All paths will be handled by serve-static-bun.

import Bao from "baojs";
import serveStatic from "serve-static-bun";

const app = new Bao();

// *any can be anything
app.get("/*any", serveStatic("web", { middlewareMode: "bao" }));

app.listen();

License

MIT

You might also like...

Fast, and friendly Bun web framework

🦊 KingWorld Fast, and friendly Bun web framework. ⚑️ Faster than Express.js by 8.5x on M1 Max Named after my favorite VTuber (Shirakami Fubuki) and c

Jan 4, 2023

A minimal routing library designed to sit on top of Bun's fast HTTP server.

siopao A minimal routing library designed to sit on top of Bun's fast HTTP server. Based on Radix Tree. Sio=Hot Pao=Bun Installation bun add siopao Us

Nov 8, 2022

⚑️ A fast, minimalist web framework for the Bun JavaScript runtime

πŸ₯Ÿ Bao.js A fast, minimalist web framework for the Bun JavaScript runtime. ⚑️ Bao.js is 3.7x faster than Express.js and has similar syntax for an easy

Dec 26, 2022

zx inspired shell for Bun/Node.

🐚 bnx zx inspired shell for Bun/Node. Install bun add bnx # npm install bnx Usage import { $ } from 'bnx' const list = $`ls -l` const files = list.

Oct 16, 2022

A zero-dependency, strongly-typed web framework for Bun, Node and Cloudflare workers

nbit A simple, declarative, type-safe way to build web services and REST APIs for Bun, Node and Cloudflare Workers. Examples See some quick examples b

Sep 16, 2022

A blazingly fast Bun.js filesystem router, with an unpleasantly smooth experience!

Oily A blazingly fast Bun.js filesystem router, with an unpleasantly smooth experience! Installation Β· Usage Β· Examples Β· Discord Installation Once yo

Dec 19, 2022

Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called

bun-livereload Wrap a function with bun-livereload to automatically reload any imports inside the function the next time it is called. import liveRelo

Dec 19, 2022

TypeScript type definitions for Bun's JavaScript runtime APIs

Bun TypeScript type definitions These are the type definitions for Bun's JavaScript runtime APIs. Installation Install the bun-types npm package: # ya

Dec 16, 2022

An express-like API for bun server

An express-like API for bun server

πŸ§„ bunrest What is bunrest πŸ‘€ bunrest is an ExpressJs-like API for bun http server. Features ⚑ BLAZING FAST. Bun is super fast... 0️⃣ dependencies, wo

Jan 2, 2023
Comments
  • You don't need to use arraybuffer and await

    You don't need to use arraybuffer and await

    https://github.com/jakobbouchard/serve-static-bun/blob/ab71176028b0c49fc94dc3758e038c9601d486b6/lib/serve-static.ts#L143-L157

    		if (file.isFile) {
    			return new Response(file.blob, {
    				headers: { ...options.headers, "Content-Type": `${getMimeType(file.blob)}; charset=${options.charset}` },
    			});
    		}
    
    		// If it is a folder and it has an index
    		if (options.index && indexFile.exists) {
    			return new Response(indexFile.blob, {
    				headers: {
    					...options.headers,
    					"Content-Type": `${getMimeType(indexFile.blob)}; charset=${options.charset}`,
    				},
    			});
    		}
    

    You don't need to use arraybuffer and await. I used it in my code because https://github.com/oven-sh/bun/issues/616

    https://github.com/gornostay25/svelte-adapter-bun/blob/b3e7449100216d2e72564d137c6c682c42c01507/src/sirv.js#L99-L102

    opened by gornostay25 4
  • fs:node is SLOW!!!

    fs:node is SLOW!!!

    Hi, fs:node is slow, use Bun special method Bun.file() check my code https://github.com/gornostay25/svelte-adapter-bun/blob/master/src/sirv.js It's was modified Sirv library for bun. check send method https://github.com/gornostay25/svelte-adapter-bun/blob/074a26d3b0c300d3d536ad1e9d29e4c77a72209f/src/sirv.js#L63-L103

    enhancement 
    opened by gornostay25 3
  • Add more options

    Add more options

    Non-exhaustive list of options to add (mostly from serve-static)

    • [x] dotfiles
    • [ ] acceptRanges
    • [ ] lastModified

    Options that are not considered or a not priority:

    • cacheControl, immutable, maxAge: You can set those easily with a header.
    • extensions: Not considered, I'm not doing pretty URLs, only static files.
    • fallthrough: Not really possible with the way things are currently, except for maybe with Bao.js.
    enhancement 
    opened by jakobbouchard 1
Owner
Jakob Bouchard
Jakob Bouchard
Fast, Bun-powered, and Bun-only(for now) Web API framework with full Typescript support.

Zarf Fast, Bun-powered, and Bun-only(for now) Web API framework with full Typescript support. Quickstart Starting with Zarf is as simple as instantiat

Zarf Framework 65 Dec 28, 2022
Gofiber with NextJS Static HTML is a small Go program to showcase for bundling a static HTML export of a Next.js app

Gofiber and NextJS Static HTML Gofiber with NextJS Static HTML is a small Go program to showcase for bundling a static HTML export of a Next.js app. R

Mai 1 Jan 22, 2022
Template of yew project, using tailwind and webpack for css, trunk for build and serve, deployable as is for github.io

Yew Template for Github.io Yew template that deployable as is for github.io (or as a normal yew template with css/scss stuffs without github.io), with

null 17 Dec 23, 2022
A util for getting data and metadata for all markdown files in a given dir. Useful for building static site generators

extract-md-data A util for getting data and metadata for all markdown files in a given dir. Useful for building static site generators. Usage Given th

Claire Froelich 2 Jan 6, 2022
mini vite, support static server, load ts files, pre-bundling.

Mini Vite δΈ­ζ–‡ Features Same structure with Vite. Support JS, TS, JSX, TSX, CSS, static files. Support public as public directory. Dependency Pre-Bundli

mysteryven 4 Sep 15, 2022
πŸ¦† lightning fast duckdb bindings for bun runtime

@evan/duckdb lightning fast duckdb bindings for bun runtime Install bun add @evan/duckdb Features ?? batteries included ?? jit optimized bindings ?? 4

evan 29 Oct 20, 2022
This repository contains an Advanced Zoom Apps Sample. It should serve as a starting point for you to build and test your own Zoom App in development.

Advanced Zoom Apps Sample Advanced Sample covers most complex scenarios that you might be needed in apps. App has reference implementation for: Authen

Zoom 11 Dec 17, 2022
Deno app to serve gmi pages on-the-fly for a gemini instance of my portfolio & blog

Aries Deno app to serve gmi pages on-the-fly for a gemini instance of my portfolio & blog Usage In order to run locally, you'll need SSL certs. You ca

Maxim 2 Jun 13, 2022
Serve file server with single zip file as file system in Deno.

zipland Serve file server with one-single zip file in Deno. Support zip just zip32 with deflated or uncompressed serving plaintext deflate Examples Yo

Yongwook Choi 18 Nov 2, 2022
πŸš€ A boilerplate with generic configurations to a Nextjs project with bun, vitest, cicd and etc

?? Next.JS Template with Linter ?? Tools: NextJS Typescript ESLint (Code Pattern) Prettier (Formatter) Husky (Pre-commit) Vitest (Unit/Integration Tes

Rodrigo Victor 8 Dec 18, 2022