Category Archives: Fulcrum

Writing JavaScript for the Server and Browser with Browserify

A few days ago I created fulcrum-node, a simple JavaScript wrapper for the Fulcrum API. The library doesn’t actually do much, but it keeps you from writing a bunch of boilerplate HTTP requests and handles some error processing.

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

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: