ariya/phantomjs — pull request #283 by jgonera (2012-06-28 22:02:08+00:00)
Title: CommonJS module support (require)

I know it's quite big, but I wanted everything to work. I tried to write descriptive commit messages, but if something is unclear, let me know.

There is still some refactoring work to be done in some of the C++ code which can be replaced with JS, but I want you to first have a look at this. The `injectJs` function could be reimplemented to use the modules underneath (or at least some of the module code). Most of the functions in `Utils` could be removed, together with the `CSConverter`. For example `Utils::findScript` can be replaced with `Module.prototype._getFilename`, the CoffeeScript can be simply required in JS.

There's a bonus functionality from the newest phantomjs-nodify version. You can stub required modules in the given module context, e.g. you have a module in file `a.js` in the same directory as your main script, which you require in the main script (`require('./a')`). Then, `a.js` contains:

```js
require.stub('path', {
join: function() { ... }
});

var something = require('some_node.js_module_that_requires_path');
```

Now `require('path')` will return the object with the `join` function in `a.js` and in every module required by it, but not in parent modules (in this case `require('path')` will throw an exception in the main script).

This is especially useful when trying to require libraries written for Node.js. It's also used internally to require the Node.js version of CoffeeScript (`src/modules/_coffee-script.js`).