节点JS Trireme包括模块
我使用Java中的https://github.com/apigee/trireme在JVM中运行Node JS。 我有一个如下所示的目录:
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中find该文件。 我没有关于节点JS的知识,所以我不熟悉模块加载。 我已经尝试设置NODE_PATH,只能得到
错误:无法find模块“请求”
似乎我无法从Trireme获得NODE_PATH,如果我覆盖它,Trireme无法运行。 我不知道如何获得在Trimere中加载的Node JS模块。 任何帮助赞赏。
编辑 :我改变了要求('./somemodule/index.js'),这工作。 所以设置NODE_PATH也可以完成这项工作。 我刚刚发现错误来自一个缺less的依赖。
"dependencies": { "request": "^2.49.0", "tough-cookie": "^0.12.1" },
我想出了处理它的最好方法是安装Node JS + npm,并调用npm在节点/文件夹中安装some_module。 它会自动将some_module及其所有依赖项下载到我的节点/文件夹中。 没有更多的要求错误。
我没有指定该文件在工作目录中。
require('./somemodule/index.js');
代替
require('somemodule/index.js');
做了这个工作。 另一种可能性是将NODE_PATH环境variables设置为节点/文件夹,因此您可以不使用./
。
我还发现获取模块的最好方法是用npm安装它们,而不是从git下载它们,因为后者不下载任何依赖关系。