Skip to content

Instantly share code, notes, and snippets.

@anba
Created July 10, 2012 14:25
Show Gist options
  • Save anba/3083613 to your computer and use it in GitHub Desktop.
Save anba/3083613 to your computer and use it in GitHub Desktop.
Using preExec-script to provide __dirname in Rhino's CommonJS implementation
// print __dirname to System.out
console.log("app.js (__dirname): " + __dirname);
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