It’s packaged up nicely as an npm package but I thought it would be helpful to make it usable in the browser as well. The fuclrum-node package depends on the request package to communicate with the API. Request uses Node’s core HTTP module, which is not available in the browser. Fortunately there’s the xhr package that wraps the a browser’s XMLHttpRequest object. xhr uses the same API as request, so so we can write our code once, with the same results on the server and in the browser.
So, how do we utilize the xhr package when we’re in the browser?
Browserify is a tool for creating node flavored modules for the browser. Running the
browserify command will package up all of your dependencies and place them in a single bundle that can be easily added to easily added to a page. It turns out browserify looks for a special “browser” field in your package.json. Here you can override specific modules that set the proper file resolution for browser-specific versions of modules. In our case we set the request module to use the xhr module.
Then we just run the browserify command to create our bundle. In the example below the
-s Fulcrum bit says build as a standalone and set the package contents to window.Fulcrum if no module system is found (in the browser).
browserify lib/index.js -s Fulcrum > fulcrum.js
Now we can reference the bundled script above and use the fulcrum node package in the browser just as we would on the server: