[英]How to use Exec / ExecFile on Javascript to run a java file and get the result
在我网站的服务器端运行这个 JS 文件,所以当用户按下一个按钮时,它会用我的 API 执行这个命令:
exports.runAlgorithm = async (req, res) => {
try {
exec('java test.java', (error, stdout, stderr) => {
if (error) {
console.error(`${error}`);
return;
}
try {
//Export the result to the database
Result.create({
//Should send the algorithm's result here
result: stdout
})
res.send({
message: "Algorithm executed successfully and output stored in database",
});
}
catch (err) {
res.send({
message: "Something went wrong when passing the data to the database",
});
console.log(`stderr: ${stderr}`);
}
});
}
catch (err) {
res.send({
message: "Problem with running the algo"
});
}
}
但我收到此错误:
exec error: Error: Command failed: java test.java
Error: Could not find or load main class test.java
Caused by: java.lang.ClassNotFoundException: test.java
运行此代码的 API 是算法 controller,刚刚返回 hello world 的测试文件是 test.java
也尝试过 execFile 替代方案但无济于事。 也许我只是错误地使用它或者有更好的方法来做到这一点。
Java 运行编译后的文件,扩展名为“.class”。
您应该使用javac编译 test.java class 。
javac test.java
然后,您应该单独使用 class 名称运行 java。
java test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.