How can I use a javascript library on the server side of a NodeJS app when it was designed to run on the client?

非 Y 不嫁゛ 提交于 2019-12-04 05:29:17

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) return console.error(err);
    run_jsrepl.call(window);
  }
});

function run_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 : )

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

  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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!