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">
  • I think, that is really long, 3 lines to expose your code? if you use coffee script, you can simply do,

    class Animal
    constructor: ->

    exports ?= Animal

    it should work, both browser and in node, since var Animal = function(){}, in browsers global scope would be as if you did window.Animal = function (){},

    What do you think?

    • Valtid, that will totally work too. You can definitely simply this down per your preferences. I left the code a little verbose, just so that it’s clear to the reader what’s going on.

  • Hamdanil R

    What if the shared code has require() lines?

    • Hamdanil, in that case, you’ll probably want to use a more advanced approach. You may want to look into browserify. The code above is just meant for simple code snippets or classes.