我正在使用 https://github.com/apigee/trireme 运行 Node JS来自 Java,在 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.h 中找到该文件。 我对Node JS一无所知,所以我不熟悉模块加载。我已经尝试设置 NODE_PATH,只是为了得到 p>
Error: Cannot find module 'request'
似乎我无法从 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,并在 node/文件夹中调用 npm install some_module 。它会自动将 some_module 及其所有依赖项下载到我的 Node/文件夹中。 不再需要错误。
最佳答案
我没有指定文件在工作目录中。
require('./somemodule/index.js');
代替
require('somemodule/index.js');
完成了任务。另一种可能性是将 NODE_PATH 环境变量设置为 node/文件夹,这样你就可以在没有 ./
.
我还发现获取模块的最佳方法是使用 npm 安装它们,而不是从 git 下载它们,因为后者不下载任何依赖项。
关于java - Node JS Trireme 包含模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682169/