Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

272
Views
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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!