Search code examples
npmrustcommand

Why I get program not found error on running "npm -v" command with Rust Command::new("npm")?


I am try to testing out version check and other things with Rust std::process::command. Other command are working fine but when I try to call npm -v, I got program not found error.

My Error:

My Error

My Code:

My Code

NPM Test:

NPM Test

I want to npm -v command runnable with rust


Solution

  • The issue is that npm isn't just npm, there's actually multiple (scripts):

    • npm
    • npm.cmd
    • npm.ps1

    When you execute npm in your terminal, then your terminal is smart and automatically picks the one it recognizes. In the same way that if you (on Windows) execute foo it will automatically run foo.exe.

    However, Command::new() does not take this into account. So when it tries to locate npm it ends up with npm (sh script) and not npm.cmd.

    You can resolve your issue by changing "npm" to "npm.cmd". To have it be a bit more flexible for other operating systems, then you can use a function like this:

    pub fn npm() -> Command {
        #[cfg(windows)]
        const NPM: &str = "npm.cmd";
        #[cfg(not(windows))]
        const NPM: &str = "npm";
    
        Command::new(NPM)
    }
    

    Then you simply replace your Command::new("npm") with npm().

    Example:

    use std::process::Command;
    
    pub fn npm() -> Command {
        #[cfg(windows)]
        const NPM: &str = "npm.cmd";
        #[cfg(not(windows))]
        const NPM: &str = "npm";
    
        Command::new(NPM)
    }
    
    fn main() -> std::io::Result<()> {
        npm().arg("-v").spawn()?.wait()?;
    
        Ok(())
    }