Created
July 10, 2012 14:25
-
-
Save anba/3083613 to your computer and use it in GitHub Desktop.
Using preExec-script to provide __dirname in Rhino's CommonJS implementation
This file contains 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
// print __dirname to System.out | |
console.log("app.js (__dirname): " + __dirname); |
This file contains 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
public class TestPreExec { | |
@Test | |
public void testPre() { | |
Context context = Context.enter(); | |
try { | |
ScriptableObject scope = context.initStandardObjects(); | |
URI uri = URI.create(TestPreExec.class.getResource(".") | |
.toExternalForm()); | |
Iterable<URI> privilegedUris = singletonList(uri); | |
Iterable<URI> fallbackUris = null; | |
ModuleScriptProvider provider = new StrongCachingModuleScriptProvider( | |
new UrlModuleSourceProvider(privilegedUris, fallbackUris)); | |
String source = ""; | |
source += "console = {log: function(s) { java.lang.System.out.println(s + '') }};\n"; | |
source += "__dirname = new java.io.File(java.net.URI.create(module.uri)).getParent();\n"; | |
Script preExec = context.compileString(source, "pre-exec", 1, null); | |
Script postExec = null; | |
boolean sandboxed = false; | |
Require require = new Require(context, scope, provider, preExec, | |
postExec, sandboxed); | |
require.requireMain(context, "app"); | |
} finally { | |
Context.exit(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment