Node JS Trireme包含模块

时间:2015-06-06 11:19:09

标签: java javascript node.js apigee bridge

我在Java中运行带有https://github.com/apigee/trireme的Node JS,在JVM中运行。我有一个看起来如下的目录:

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

使用此代码运行test_file.js没有问题:

@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());
    }
}

在文件test_somemodule.js中,我包含index.js。

require('somemodule/index.js');

当我尝试运行该文件时,它无法在require中找到该文件。 我不了解Node JS,所以我不熟悉模块加载。我已经尝试过设置NODE_PATH,只是为了获取

  

错误:无法找到模块'请求'

好像我无法从Trireme获得NODE_PATH,如果我覆盖它,Trireme就无法运行。我是如何在Trimere中加载Node JS模块的想法。任何帮助表示赞赏。

修改:我将需要更改为(' ./ somemodule / index.js'),这有效。所以设置NODE_PATH也可以完成这项工作。我刚发现错误来自缺少的依赖。

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

我想出了处理它的最佳方法是安装Node JS + npm,并在节点/文件夹中调用npm install some_module。它会自动将some_module及其所有依赖项下载到我的节点/文件夹中。 不再需要错误。

1 个答案:

答案 0 :(得分:2)

我没有指定该文件位于工作目录中。

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

而不是

require('somemodule/index.js');

完成了这项工作。另一种可能性是将NODE_PATH环境变量设置为节点/文件夹,因此您可以不需要./

我还发现获取模块的最佳方法是使用npm安装它们而不是从git下载它们,因为后者不会下载任何依赖项。

相关问题