I just got the task to create a java file, that works as JavaScript under Node.js, and as Java code also. The file extension has to be .java. My question is - how can I even run the .java file in the node? I wasn't able to find anything about an issue like this. The code itself is very simple, so the only thing is - how to run .java in node?
I can't use npm pack. It must be vanilla code.
so
node test.java > output
javac test.java && java test > output
With the normal API, unless you use Wasmer and run it with WebAssembly, (which I doubt you want to do, especially considering you can't use npm packages), you can not do this with a java running library inside.
However, you can spawn a child process to run it:
const { exec } = require('child_process');
exec('javac Main.java', (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
exec('java Main', (err, stdout, stderr) => {
if (err) {
console.error(`exec error: ${err}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
})
});
Though, I highly advise to port the Java code you have to Node.JS.