从 node.js 文件调用 npx

Eri*_*ric 3 node.js npm npx

我尝试过使用execbash 文件,我尝试过使用直接调用,我尝试过深入研究 npm 和 npx 文档,但这个问题似乎没有答案:how can an npx call be returned from node.js代码?

触发与 npx 调用相同的功能而不实际编写为 npx 调用的答案也是可以接受的。

小智 5

我不太确定你的问题出在哪里......

  • npx一般如何调用脚本?
  • 从节点内运行 shell 命令?
  • 专门运行npx命令?您遇到错误了吗?

运行 shell 命令的最广泛的方法是child_process,我不知道为什么你不能直接npx在其中放置一个命令(我刚刚测试了它npx --help并且有效):

const { exec } = require("child_process");

exec("echo Hello World", (err, stdout, stderr) => {
  if (err) {
    console.error();
    console.error("Error:");
    console.error(err);
    console.error();
  }
  console.log(stdout);
  console.error(stderr);
});
Run Code Online (Sandbox Code Playgroud)

现在,这可能就是您所说的“尝试使用”的意思exec,而您只是在这样做时遇到错误。当然,在这种情况下出现该错误会很有帮助,但也许是npx没有找到。

确保你已经安装了 npx - 也许只是npm虚拟环境无法访问它,所以你可以使用npm install npx它来安装它。如果您使用 运行它npm,请确保它已全局安装:npm install -g npx

如果是其他问题,请提供有关您到底缺少什么或您遇到的潜在错误的更多信息。