I am trying to run a java class file from a different directory. However, it always gives the error "Could not find or load main class {dirpath}"
My project directory is as follows:
- NodeProject
- code
- Main.java
- javaClasses
- index.js
"code" folder contains java src files, that I take as input from a candidate/user and save it as filename.java and a folder "javaClasses", which should contain the .class file after compilation.
index.js is my entry point which runs via npm start
my index.js code is as follows:
const spawnSync = require("child_process").spawnSync;
const { exec } = require("child_process")
const path = require('path');
let filepath = path.join(__dirname, "code", "Main.java");
let dirpath = path.join(__dirname, "code", "javaClasses");
let folderPath = path.join(__dirname, "code");
const run = async (command, args) => {
let options = "";
let output = spawnSync("javac", ["-d", dirpath, filepath]); /// creates Main.class file in javaClasses folder
exec(`${command} "${args}" | java -cp ${dirpath} Main`, (error, stdout, stderr) =>{
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
}
let s ="22"
run("printf", [s]);
.class file is succesfully compiled, exec command is giving the error.
I tried replacing dirpath with folderpath where the actual src file is but to no avail.
I saw somewhere to try cd {path} & java Main but it still doesn't work and give the same error.
Also, my src file doesn't have any package import like package code, since i take the whole src file from user input.
Any help will be very much appreciated!.