Skip to content

How can I use a child process to run a .class file from a parent directory?

In this case, I am using Node.js ChildProcess. Let’s say the application file (index.js, for example) is in folder1. This folder also has folder2, which is where the class file is. So, when I call spawn from folder1, the command’s current directory is folder1. However, I can’t do java ./folder2/MyFile.

Here’s what I tried:

async function run(path){
    let child = spawn('java', [path], {
            stdio: [process.stdin, process.stdout, process.stderr] //for testing purposes

Using function run on ./folder2/MyFile returns:

Error: could not find or load main class ..folder2.MyFile

I assume this has something to do with java and classpath. I saw an answer involving setting the classpath to the target directory (folder2) but it didn’t do anything.

In short, how can I run a .class file from a different directory?



You can use exec instead of spawn so you can use two commands with & symbol which the second command runs when the first one finish without fail. I think this might work for you.

const exec = require('child_process').exec;
exec("cd ./folder2 & java MyFile", function(
    error: string,
    stdout: string,
    stderr: string
) {
User contributions licensed under: CC BY-SA
7 People found this is helpful