Skip to content

Instantly share code, notes, and snippets.

@piglovesyou
Last active August 29, 2015 14:16
Show Gist options
  • Save piglovesyou/57ad4f602bfe189b0900 to your computer and use it in GitHub Desktop.
Save piglovesyou/57ad4f602bfe189b0900 to your computer and use it in GitHub Desktop.
Load CommonJS JavaScript module, call function in it with Rhino
import java.util.Arrays;
import java.util.List;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.commonjs.module.Require;
import org.mozilla.javascript.tools.shell.Global;
public class Test{
public static void main(String[] args){
// assume first arg is ":" delimited paths to directories containing modules
List<String> modulePaths = Arrays.asList(args[0].split(":"));
// assume second arg is id for main module
String mainModuleId = args[1];
Context context = Context.enter();
context.setLanguageVersion(170);
try {
// Create Common JS context
Global global = new Global();
global.initStandardObjects(context, true);
Require require = global.installRequire(context, modulePaths, false);
// Run and Load main module
Scriptable exports = require.requireMain(context, mainModuleId);
// Print property value of the main module
String myProperty = (String)exports.get("myProperty", exports);
System.out.println(myProperty);
// Call function in the main module
Function fn = (Function)exports.get("addFunction", exports);
Object result = fn.call(context, global, global, new Object[] {2, 3});
System.out.println(result); // 5.0
} finally {
Context.exit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment