Giter Club home page Giter Club logo

serve-static-bun's Introduction

serve-static-bun

npm version npm bundle size npm downloads

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 null. 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. Is not defined by default (no stripping).

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 if the pathname needs to be changed.

dotfiles

This option allows you to configure how the module handles dotfiles, i.e. files or directories that begin with a dot ("."). Dotfiles return a 403 by default (when this is set to "deny"), but this can be changed with this option.

defaultMimeType

The default mime type to send in the "Content-Type" HTTP header, when the file's cannot be determined. Defaults to text/plain.

charset

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

Middleware mode options

middlewareMode

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

handleErrors

If set to false, in the case of a 403 or 404 response, the unmodified context will be returned to Bao.js. This allows you to handle the error yourself.
If set to true, the error response will be sent to the client, without continuing the middleware chain.
Defaults to false.

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

serve-static-bun's People

Contributors

gornostay25 avatar jakobbouchard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

lazuee

serve-static-bun's Issues

Remove process.cwd() as root folder

Why there's a need to add process.cwd()? Give us the freedom to use absolute path...
https://github.com/jakobbouchard/serve-static-bun/blob/7ed89cd0d142844f73ac158b0fcb351553cc89dc/src/serve-static.ts#L236C1-L236C36

I can't do like this because of that process.cwd() as root prefix..

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

const app = new Bao();
const staticFolder = path.join(import.meta.dir, "..", "/public");
app.get("/gamefiles/*any", serveStatic(staticFolder, { middlewareMode: "bao", stripFromPathname: "/gamefiles" }));

Add more options

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

  • 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.

You don't need to use arraybuffer and await

if (file.isFile) {
return new Response(await file.blob.arrayBuffer(), {
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(await indexFile.blob.arrayBuffer(), {
headers: {
...options.headers,
"Content-Type": `${getMimeType(indexFile.blob)}; charset=${options.charset}`,
},
});
}

		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 oven-sh/bun#616

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

using `.` as the directory causes weird issues

import serveStatic from 'serve-static-bun';

const serve = serveStatic('.', {
  collapseSlashes: true,
});

Bun.serve({
  port: 3000,
  fetch: serve,
});
  bun-rsc git:(main)  bun run ./src/file.ts                                         
Response (4.50 PB) {
  ok: true,
  url: "",
  status: 200,
  statusText: "",
  headers: Headers {
    "content-type": "text/javascript; charset=utf-8",
  },
  redirected: false,
  bodyUsed: false,
  FileRef ("/Users/luna/code/imlunahey/bun-rsc/.//build/_client.js") {
    type: "text/javascript;charset=utf-8"
  }
}
[1]    19614 segmentation fault  bun run ./src/file.ts
  bun-rsc git:(main)  bun run ./src/file.ts
[1]    19658 segmentation fault  bun run ./src/file.ts
  bun-rsc git:(main)  ls -lah /Users/luna/code/imlunahey/bun-rsc/.//build/_client.js
-rw-r--r--  1 luna  staff   1.2M Dec 26 12:41 /Users/luna/code/imlunahey/bun-rsc/.//build/_client.js

Support for absolute paths

Currently if i provide an absolute path it's added to the end of the process.cwd() which is not what i was expecting at all. 🤔

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.