Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run NPM Command in Java code using ProcessBuilder

Tags:

java

npm

My environment is mac. I'm trying to run "npm ls" from my java code but it throws error messages.

My java code:

String npm = isWindows() ? "npm.cmd" : "npm";

System.out.println(rootStr);
Process process = new ProcessBuilder(npm, "ls").directory(new File(rootStr)).start();

Error Message:

Users/youngeun/Downloads/zenbot_unstable
java.io.IOException: Cannot run program "npm" (in directory "/Users/youngeun/Downloads/zenbot_unstable"): error=2, No such file or directory
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    at com.iotcube.scanner.nodejs.npm.NpmService.npmInfo(NpmService.java:26)
    at com.iotcube.scanner.IotcubescannerApplication.main(IotcubescannerApplication.java:174)
Caused by: java.io.IOException: error=2, No such file or directory
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:247)
    at java.lang.ProcessImpl.start(ProcessImpl.java:134)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    ... 2 more

But it seems to work perfectly in my terminal:

| ~/Downloads/zenbot_unstable @ Youngeunui-MacBook-Pro (youngeun) 
| => npm ls
[email protected] /Users/youngeun/Downloads/zenbot_unstable
├─┬ @babel/[email protected]
│ ├─┬ @babel/[email protected]
│ │ └─┬ @babel/[email protected]
│ │   ├── [email protected] deduped
│ │   ├── [email protected] deduped
│ │   └── [email protected]
│ ├─┬ @babel/[email protected]
│ │ ├── @babel/[email protected] deduped
│ │ ├── [email protected]
│ │ ├── [email protected] deduped
...

I've tried solutions from other stackoverflow pages but none of them seems to work... I am so lost.. I would appreciate your help. thanks

like image 896
youngeun Avatar asked Oct 21 '25 06:10

youngeun


1 Answers

Try providing full path to the npm executable:

String dir = "/Users/youngeun/Downloads/zenbot_unstable";
String npm = dir + "/npm";
Process p = new ProcessBuilder(npm, "ls")
                .director(new File(dir))
                .start();
p.waitFor();
like image 137
Karol Dowbecki Avatar answered Oct 23 '25 20:10

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!