Skip to content Skip to sidebar Skip to footer

How Can I Use A Javascript Library On The Server Side Of A Nodejs App When It Was Designed To Run On The Client?

I'm diving into NodeJS and Express (it's sooo complicated to me) to build a real-time web app. At the moment, I'm trying to understand how I can use an existing javascript library

Solution 1:

So this is possible, but you need some serious hackery in order to get it working. Since this is not a node module and is written from the browser as others have noted, you need a DOM within node to execute it into. Luckily, we have the wonderful jsdom project which allows us to do just that. So let's get this thing set up.

  • cd into your node project (create one if there isn't one already)
  • clone down the jsrepl repo git clone git://github.com/replit/jsrepl.git
  • cd into jsrepl and initialize submodules git submodule update --init --recursive
  • still in the folder, run npm install coffee-script and npm install uglify-js, dependencies that are not mentioned anywhere in the repo (ugh).
  • make sure java is installed and run cake bake. After a lengthy process of compiling java files and such the command will finish and jsrepl will be built and ready to go.
  • run npm install jsdom, then we can start writing an example file

Here's a minimal example:

var jsdom = require('jsdom'),
    fs = require('fs'),
    jsrepl = fs.readFileSync('./jsrepl/repl.js', 'utf8');

jsdom.env({
  html: "<script src='jsrepl.js' id='jsrepl-script'></script> ",
  src: [jsrepl],
  done: function(err, window){
    if (err) returnconsole.error(err);
    run_jsrepl.call(window);
  }
});

functionrun_jsrepl(){
  console.log(this.JSREPL)
}

Here's the minimum amount of code required to get JSREPL into a place where it's working. All we're doing here is requiring jsdom and instantiating it, reading in the jsrepl source straight from the file. If you run this file with node filename it will log out your JSREPL object, which can be used just like it's in the browser : )

Solution 2:

You can run phantomjs in Node, which is a headless webkit browser. Then run jsrepl inside of phantomjs.

Solution 3:

  1. No. There are things on the client side that you don't have on the server side (and vice-versa): for instance, the DOM.
  2. I've never worked with jsrepl myself, but assuming that it's platform-agnostic, require()ing it from a node module should be OK. However, there seem to be some DOM-specific things in the scripts in question (e.g. document.getElementById) that suggest otherwise.

Post a Comment for "How Can I Use A Javascript Library On The Server Side Of A Nodejs App When It Was Designed To Run On The Client?"