Last active
August 29, 2015 14:16
-
-
Save piglovesyou/57ad4f602bfe189b0900 to your computer and use it in GitHub Desktop.
Load CommonJS JavaScript module, call function in it with Rhino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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