使用 Rust 安装 NPM 包 std::process::Command
Installing NPM package with Rust std::process::Command
我正在尝试以编程方式安装 NPM 包作为 Rust 程序的一部分。
我正在使用 std::process::Command
结构,并且可以成功 运行 节点:
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(())
}
上面的代码returns:
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()?;
我正在尝试以编程方式安装 NPM 包作为 Rust 程序的一部分。
我正在使用 std::process::Command
结构,并且可以成功 运行 节点:
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(())
}
上面的代码returns:
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 anErr
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()?;