Sharing Javascript Between Backend (Node.js) and Frontend (Browser)

I’ve always liked the idea of being able to reuse Javascript code in both Node.js (on the backend) and the browser (on the frontend). I finally ran into a situation this weekend where it was practical to do this and I was surprised by just how easy it was to do. I thought I’d throw my solution into a post. The code below is written in CoffeeScript.

# Define my class
class myClass
  # Define a method within my class
  doSomething: ->
    console.log("Hello world!")

# Add to exports for node, or window for browser
if typeof module isnt 'undefined' and module.exports
  module.exports = new myClass()
  this.myClass = new myClass()

First, we create a class named "myClass" and add a method to it. Then, with a simple if statement, we can determine whether we’re running this code in Node.js or in the browser and export the class accordingly. Let’s assume we’re compiling this down into "my-class.js".

In Node.js, we would use the class like this:

myClass = require("my-class")

In the browser, we would use the class like this:

<script type="text/javascript" src="my-class.js"></script>
<script type="text/javascript">