[英]How to execute a package.json script from a node.js script file?
Let's imagine that we have such package.json scripts section:假设我们有这样的 package.json 脚本部分:
{
"name": "myProject",
"version": "0.0.1",
"scripts": {
"compile": "npm run lint:fix && tsc",
},
}
We can execute this script via CMD by: npm run compile
我们可以通过 CMD 执行这个脚本,方法是: npm run compile
How to do it via any Node.js script?如何通过任何 Node.js 脚本来做到这一点?
Eg.例如。 I want to run the script file and these commands should execute.我想运行脚本文件,这些命令应该执行。
I'm interested in any option: Run the package.json script from the node script or just run the commands separately in the script somehow.我对任何选项都感兴趣:从节点脚本运行 package.json 脚本,或者以某种方式在脚本中单独运行命令。
You can use exec
from node.js and it will execute shell commands:您可以使用 node.js 中的exec
,它将执行 shell 命令:
const { exec } = require("child_process");
exec("npm run compile", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.