简体   繁体   English

使用Rust std :: process :: Command安装NPM软件包

[英]Installing NPM package with Rust std::process::Command

I am trying to programmatically install an NPM package as part of a Rust program. 我正在尝试以编程方式安装NPM软件包作为Rust程序的一部分。

I am using the std::process::Command struct, and can successfully run Node with: 我正在使用std::process::Command结构,并且可以使用以下std::process::Command成功运行Node:

pub fn check_for_node(&mut self) -> Result<(), Box<dyn Error>> {
    println!("Node Version: ");
    let node = process::Command::new("node")
        .arg("-v")
        .status()?;

    self.node_is_installed = node.success();
    Ok(())
}

The code above returns: 上面的代码返回:

Node Version:
v10.15.1

with no error. 没有错误。

However, when I run: 但是,当我运行时:

pub fn install_puppeteer(&mut self) -> Result<(), Box<dyn Error>> {
    if self.node_is_installed {
        let npm = process::Command::new("npm")
            .arg("install")
            .arg("puppeteer")
            .status()?;
        self.puppeteer_is_installed = npm.success();
    }
    Ok(())
}

I get the error: 我得到错误:

thread 'main' panicked at 'called Result::unwrap() on an Err value: Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." 线程'main'对Err值的调用Result::unwrap()感到惊恐:Os {代码:2,种类:NotFound,消息:“系统找不到指定的文件。” }', src\\libcore\\result.rs:999:5 }',src \\ libcore \\ result.rs:999:5

If I run npm -v manually, I get 6.4.1 printed, so I know that NPM is installed. 如果我手动运行npm -v ,则会得到6.4.1打印,因此我知道已安装NPM。

Is there any reason that std::process::Command would work for Node and not for NPM, and is there any way to fix it? std::process::Command是否有任何理由适用于Node而不适用于NPM,是否有任何解决方法?

I was able to fix the issue by changing the working directory to C:\\Program Files\\nodejs prior to to running the command with: 通过运行以下命令之前,我可以通过将工作目录更改为C:\\Program Files\\nodejs来解决此问题:

let npm = Path::new("C:\Program Files\nodejs");
assert!(env::set_current_dir(&npm).is_ok());

After changing the working directory to my Node install path, I was able to successfully run: 将工作目录更改为Node安装路径后,我能够成功运行:

 let npm = process::Command::new("npm.cmd")
      .arg("install")
      .arg("-g")
      .arg("puppeteer")
      .status()?;

I am on Windows, but to make this answer cross platform the following code could be used: 我在Windows上,但是要跨平台做出此答案,可以使用以下代码:

#[cfg(windows)]
pub const NPM: &'static str = "npm.cmd";

#[cfg(not(windows))]
pub const NPM: &'static str = "npm";

...

 let npm = process::Command::new(NPM)
      .arg("install")
      .arg("-g")
      .arg("puppeteer")
      .status()?;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM