2015-06-06 108 views
2

我在JVM内部运行来自Java的带有https://github.com/apigee/trireme的Node JS。我有一个目录,看起来如下:节点JS Trireme包含模块

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中找到该文件。 我不知道节点JS,所以我不熟悉模块加载。我已经尝试设置NODE_PATH,只拿到

Error: Cannot find module 'request'

好像我无法从三列桨座战船的NODE_PATH,如果我将其覆盖,三列桨座战船无法运行。我对如何获得在Trimere中加载的Node JS模块没有想法。任何帮助赞赏。

编辑:我将require改为('./somemodule/index.js'),它工作。所以设置NODE_PATH也会完成这项工作。我刚刚发现错误来自缺失的依赖关系。

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

我想出了对付它正在安装节点JS + NPM,并调用NPM在节点/文件夹中安装some_module的最佳途径。它会自动将some_module及其所有依赖项下载到我的节点/文件夹中。 不再需要错误。

+0

编辑实际上回答你的问题,不是吗? :P –

+0

@ E_net4是的,它的确如下:D你会推荐创建一个答案还是只是让问题保持原样? – Zackline

+1

不要**留下问题,因为它是。将答案部分移至您自己的答案。 –

回答

1

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

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

代替

require('somemodule/index.js'); 

做的工作。另一种可能性是将NODE_PATH环境变量设置为节点/文件夹,因此您可以在不需要./的情况下执行此操作。

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