How to run NPM Command in Java using Process Builder

后端 未结 2 1388
遥遥无期
遥遥无期 2021-01-07 06:29
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import         


        
相关标签:
2条回答
  • 2021-01-07 07:22

    The problem is that ProcessBuilder does not respect the PATHEXT variable on Windows.

    It's true there is no npm binary on Windows, there's a npm.cmd. My best solution is to check the platform. Something like this:

    static boolean isWindows() {
        return System.getProperty("os.name").toLowerCase().contains("win");
    }
    
    static String npm = isWindows() ? "npm.cmd" : "npm";
    
    static void run() {
        Process process = new ProcessBuilder(npm, "update")
                .directory(navigatePath)
                .start()
    }
    
    0 讨论(0)
  • 2021-01-07 07:23

    In Unix or Linux os , the PathBuilder takes the default environment path , so we have to change the environment path and run the npm command through the bash.

        package com.ainosoft.space.manager.command.executor;
        import java.io.File;
        import java.util.Map;
    
        public class CommandExecutor {
        public void exceuteCommand(String commandString,String 
        directoryToExecuteCommand) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(new String{"bash", "-c",commandString});
            Map<String, String> env = processBuilder.environment();
            processBuilder.directory(new File(directoryToExecuteCommand));
            String envPath="/home/admin123/.nvm/versions/node/v10.15.3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin";
            env.put("PATH",envPath);
            processBuilder.start();
         } catch (Exception e) {
            e.printStackTrace();
       }
    
      }
    public static void main(String args[]) {
        CommandExecutor commandExecutor=new CommandExecutor();
        commandExecutor.exceuteCommand("npm install", "/home/admin123/Desktop");
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题