gpt4 book ai didi

java - 从java应用程序执行node.js脚本时出现问题

转载 作者:行者123 更新时间:2023-12-02 07:00:42 24 4
gpt4 key购买 nike

当我尝试从 java 类执行 node.js 脚本时,出现以下错误:java.io.IOException:无法运行程序“node events.js”:错误=2,没有这样的文件或目录

这是我的代码,有人可以告诉我我在这里缺少什么吗?

public class NodeInitializer {
private static final Logger logger = Logger.getLogger(SpringLauncher.class);
private Process nodeProcess;
ProcessBuilder processBuilder;

public void start(){
try {
processBuilder = new ProcessBuilder("node events.js");
nodeProcess = processBuilder.start();
} catch (IOException e) {
logger.error(e.getCause(), e);
}
}
}

最佳答案

使用

List<String> commands = new LinkedList<String>();
commands.add("node");
commands.add("event.js");

ProcessBuilder processBuilder = new ProcessBuilder(commands);
processBuilder.start();

javadoc for ProcessBuilder

a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves - on such a system a Java implementation might require commands to contain exactly two elements.

根据我的经验,大多数操作系统要求您对要执行的命令中的元素进行标记,因此 [node](命令/程序)[events.js](参数) 为列表中的两个元素。

你正在得到

 java.io.IOException: Cannot run program "node events.js": error=2, No such file or directory

因为 java 通过操作系统尝试将“node events.js”作为程序执行,而不是作为程序及其参数执行。

关于java - 从java应用程序执行node.js脚本时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16699888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com