0

When I try to execute my node.js script from a java class I get the following error: java.io.IOException: Cannot run program "node events.js": error=2, No such file or directory

here is my code can someone tell me what am I missing here?

public class NodeInitializer {
    private static final Logger logger = Logger.getLogger(SpringLauncher.class);    
    private Process nodeProcess;
    ProcessBuilder processBuilder;

    public void start(){
        try {
            processBuilder = new ProcessBuilder("node events.js");
            nodeProcess = processBuilder.start();
        } catch (IOException e) {
            logger.error(e.getCause(), e);
        }
    }
}

1 Answer 1

2

Use

List<String> commands = new LinkedList<String>();
commands.add("node");
commands.add("event.js");

ProcessBuilder processBuilder = new ProcessBuilder(commands);
processBuilder.start();

The javadoc for ProcessBuilder states

a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves - on such a system a Java implementation might require commands to contain exactly two elements.

In my experience, most OS's require you to tokenize the elements in the command you want to execute, so [node] (the command/program) [events.js] (the argument) as two elements in a list.

You are getting

 java.io.IOException: Cannot run program "node events.js": error=2, No such file or directory

because java, through the OS, is trying to execute "node events.js" as a program, not as a program and its argument.

Sign up to request clarification or add additional context in comments.

3 Comments

I edited and used the lis of arguments as you stated but what a get now is java.io.IOException: Cannot run program "node": error=2, No such file or directory and its on my system Path, do I have to set the variable?
@B.TIger try to put the full path of the node.. for ie: c:\\nodejs\node
yes it worked from the timeline The JVM wasn't Identifying my variables so I set the path for the script and the node program on a properties file that can be altered after implementation if needed thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.