简体   繁体   中英

How to use Exec / ExecFile on Javascript to run a java file and get the result

Running this JS file on the server side of my website so when the user presses a button, it executes this command with my 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"
        });
    }
}

But I receive this error:

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

The API to run this code is the algorithm controller and the test file that just returns hello world is the test.java

Have also tried the execFile alternative but to no avail. Perhaps I'm just using it wrongly or there's a better way to do this.

Java runs compiled files, with ".class" extension.
You should compile you test.java class using javac .

javac test.java

Then, you should run java with the class name alone.

java test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM