Hacker News new | ask | show | jobs
by apitman 846 days ago
Seeing Bun/Node/Deno support reminds me of a question: are there any good resources on writing JS that works in all 3 and the browser? For example if I wanted to write a simple filesystem API that would work the same across bunodeno?
3 comments

I think you'd have to write a facade package with a consistent API that mapped to the node/deno/bun equivalents, since they're each quite different.

Best bet is to use the Node fs package and rely on the deno/bun compatibility layer.

More generally, Deno pushes for Web Platform APIs, and as more are proposed and implemented the runtime-specific APIs will become fewer and fewer.

Yeah this is basically what I'm trying to do (see response to sibling). Unfortunately I consider Node's APIs the worst of the 3. No shade on them it's just an older design. I really like Deno's approach since my code also needs to work in the browser. Writing HTTP handlers that take Request[0] and return Response[1] is a beautiful bit of symmetry with frontend code and feels like cheating.

[0]: https://developer.mozilla.org/en-US/docs/Web/API/Request

[1]: https://developer.mozilla.org/en-US/docs/Web/API/Response

If you use Node 20+ then there's a lot more compatibility with web platform APIs, so it is possible to write code that works on Node, browser and WinterCG-compatible runtimes like Deno. Obviously you'll need to avoid using Node builtins.
Bun’s goal is to be an actual superset of node, so you can write just for node and expect it to work in bun.

As for deno, I think if you publish ESM you’re mostly covered since deno can install from the npm registry.

You can't, and for good reason. Deno has slightly different API's than Node. Bun also has subtle differences between their STL implementation and Node's, but afaik, they're getting there.
I think maybe I was unclear. I'm talking about writing libraries that abstract across these differences and provide a single API, as sibling describes. I already know it's possible. I made a simple filesystem abstraction here[0] and a very simple HTTP library that uses it here[1]. They both work in Node/Deno and the browser. Unfortunately I ran into issues with Bun's slice implementation[2], but that should be fixed eventually.

My overall question is that I suspect there's a much better way of detecting and using the different backends, and I'm wondering what techniques are out there.

[0]: https://github.com/waygate-io/fs-js

[1]: https://github.com/waygate-io/http-js

[2]: https://github.com/oven-sh/bun/issues/7057