ehttp icon indicating copy to clipboard operation
ehttp copied to clipboard

Support for nodejs

Open robrennie opened this issue 2 years ago • 7 comments

Perhaps I'm doing something wrong, but when I use wasm-pack with a --target of nodejs and then run in a simple node test script, it panics as shown below.

panicked at 'called Option::unwrap() on a None value', ...\ehttp-0.3.0\src\web.rs:37:36

It seems this points to code that is expecting it to be run in a browser. Any chance there may be a way to support node?

Thanks!

robrennie avatar Aug 08 '23 21:08 robrennie

Yes, ehttp currently expects to run in a browser.

If you want node support, you'll have to build it :) It shouldn't be too hard - just remove the calls to web_sys::window() and replace the fetch_with_request with whatever the equivalent is in nodejs

emilk avatar Sep 07 '23 17:09 emilk

Yes, I could write it, but I figured I'd ask you to write it first :)

The hard part isn't the code, it's detecting what wasm-pack is targeting from within Rust: https://github.com/rustwasm/wasm-pack/issues/795#issue-568423906

robrennie avatar Sep 19 '23 16:09 robrennie

Hey @robrennie, @emilk, as Node.js now supports the fetch API (since v18.0), we can easily bypass the web_sys::window() + fetch_with_request call by directly mapping fetch as external function (this is what web_sys does internally).

This simple code does the trick:

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_name = fetch)]
    fn fetch_with_request(input: &web_sys::Request) -> Promise;
} 

If I find some time in the coming days, I'll make a PR.

lvauvillier avatar Jul 18 '24 13:07 lvauvillier

Hi @lvauvillier - I think you'll still run into the conditional compilation problem with wasm-pack (see the comment above) where you can't access the --target parameter to tell whether you're targeting nodejs or web.

robrennie avatar Jul 18 '24 17:07 robrennie

The code is isomorphic, functioning seamlessly on both Node (since v18.0) and the browser. So, no conditional compilation is needed.

in browsers fetch === window.fetch

lvauvillier avatar Jul 18 '24 17:07 lvauvillier

@lvauvillier - well that's pretty great! Didn't realize - I'm more a Rustacean than a javascripter. Looking forward to a new version with this!

robrennie avatar Jul 18 '24 18:07 robrennie

@robrennie I made the PR

lvauvillier avatar Jul 19 '24 16:07 lvauvillier