gpt4 book ai didi

rust - 使用 Rust std::process::Command 安装 NPM 包

转载 作者:行者123 更新时间:2023-11-29 08:31:12 25 4
gpt4 key购买 nike

我正在尝试以编程方式安装 NPM 包作为 Rust 程序的一部分。

我正在使用 std::process::Command struct,并且可以成功运行 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(())
}

上面的代码返回:

Node Version:
v10.15.1

没有错误。

但是,当我运行时:

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(())
}

我得到错误:

thread 'main' panicked at 'called Result::unwrap() on an Err value: Os { code: 2, kind: NotFound, message: "The system cannot find the file specified." }', src\libcore\result.rs:999:5

如果我手动运行 npm -v,我会打印 6.4.1,所以我知道 NPM 已安装。

std::process::Command 适用于 Node 而不适用于 NPM 是否有任何原因,是否有任何方法可以修复它?

最佳答案

在运行命令之前,我能够通过将工作目录更改为 C:\Program Files\nodejs 来解决问题:

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

将工作目录更改为我的 Node 安装路径后,我能够成功运行:

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

我在 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()?;

关于rust - 使用 Rust std::process::Command 安装 NPM 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57310019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com