Search code examples
javajavascriptnode.jsapigeebridge

Node JS Trireme include module


I'm running Node JS with https://github.com/apigee/trireme from Java, inside the JVM. I have a directory that looks as following:

node/
-test_file.js
-test_somemodule.js
-somemodule/
-somemodule/index.js
-somemodule/...

I have no problem running the test_file.js using this code:

@Test
public void shouldRunTestScript() {
    try {
        NodeEnvironment env = new NodeEnvironment();
        // Pass in the script file name, a File pointing to the actual script, and an Object[] containg "argv"
        NodeScript script = env.createScript("my-test-script.js",
                new File(Settings.getInstance().getNodeDir() + "/my-test-script.js"), null);
        // Wait for the script to complete
        ScriptStatus status = script.execute().get();
        // Check the exit code
        assertTrue("Exit code was not 77.", status.getExitCode() == 77);
    } catch (NodeException | InterruptedException | ExecutionException ex) {
        Logger.getLogger(TriremeTest.class.getName()).log(Level.SEVERE, null, ex);
        fail("Trireme triggered an exception: " + ex.getMessage());
    }
}

In the file test_somemodule.js I include the index.js.

require('somemodule/index.js');

When I try to run that file, it can't find the file in the require. I have no knowledge about Node JS, so I'm not familiar with the module loading. I already tried setting NODE_PATH, only to get

Error: Cannot find module 'request'

It seems like I can't obtain the NODE_PATH from Trireme, and if I overwrite it, Trireme fails to run. I'm out of ideas on how I could get an Node JS module loaded in Trimere. Any help appreciated.

Edit: I changed the require to ('./somemodule/index.js'), which works. So setting the NODE_PATH would have done the job too. I just found out the error came from an missing dependency.

  "dependencies": {
"request": "^2.49.0",
"tough-cookie": "^0.12.1"
 },

I figured out the best way to deal with it is installing Node JS + npm, and invoking npm install some_module in the node/ folder. It automatically downloads some_module and all of its dependencies into my node/ folder. No more require errors.


Solution

  • I did not specify that the file was in the working directory.

    require('./somemodule/index.js');
    

    instead of

    require('somemodule/index.js');
    

    did the job. Another possiblity is to set the NODE_PATH environment variable to the node/ folder, so you can require without ./.

    I also figured out that the best way to obtain modules is by installing them with npm instead of downloading them from git, because the latter does not download any dependencies.