node-server icon indicating copy to clipboard operation
node-server copied to clipboard

add support for absolute path to serveStatic root

Open charlyoleg2 opened this issue 1 year ago • 4 comments

Could you add support for absolute path for the root of the serveStatic? In my use-case designix-uis, an absolute path to the folder containing the static files is required as tool can be called from any directory. Currently i"m using Express, but i"d like to replace it with Hono and this feature is missing. The following patch in the file src/serve-static.ts might be sufficient for supporting the absolute path:

-      path = addCurrentDirPrefix(path)
+      if (!/^\//.test(path)) {
+        path = addCurrentDirPrefix(path)
+      }

charlyoleg2 avatar Aug 17 '24 00:08 charlyoleg2

Hi @charlyoleg2

We may add supporting it.

Related to: https://github.com/honojs/hono/pull/3108 https://github.com/honojs/node-server/pull/78

yusukebe avatar Aug 19 '24 00:08 yusukebe

@yusukebe I just ran into the absolute path issue as well 😅

DoWhileGeek avatar Aug 22 '24 03:08 DoWhileGeek

The hono's release 4.3.6 supports absolute path for serveStatic. Now node-server must forward the path without modifying it. This will enable the feature working in nodejs. The current release 1.13.1 of node-server prefixes the path with './'. This prevents the use of absolute path.

charlyoleg2 avatar Sep 28 '24 06:09 charlyoleg2

I'm developing a package that I expect people to run using "npx" from any directory too, it would be very helpful to be able to use absolute paths (or a relative path from the hono file, that would be even better).

For now, I managed to work around this by getting the relative path from wherever the user is running it from, to my compiled node script. Then I use that as the root path for serving static files.

// Hono expects the root/path in serveStatic to be relative to the working directory
// where this file is being executed from. This finds the relative path from the working directory
// to the parent folder of this file, then we can use it to point to the web build files.
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const relativePathToScript = path.relative(process.cwd(), __dirname);

// Serve web app (index.html at the root path "/", assets at "/_app/*" and favicon at "/favicon.png")
app.get("/", serveStatic({ root: relativePathToScript, path: "web/index.html" }));
app.get("/favicon.png", serveStatic({ root: relativePathToScript, path: "web/favicon.png" }));
app.use("/_app/*", serveStatic({ root: `${relativePathToScript}/web` }))

Note that if the relativePathToScript potentially needs to go up directories with ../ portions, it must be placed in the root param and not in the path param. I only realised this after a lot of confusion and frustration 🙈

Hope this is helpful to anyone else with similar requirements!

siyant avatar Feb 13 '25 04:02 siyant