【问题标题】:How to access terminal in Nodejs如何在 Nodejs 中访问终端
【发布时间】:2021-09-09 06:09:55
【问题描述】:
我想构建一个 nodejs 应用程序,它会为我做一些自动工作。但我想知道我是否可以在 nodejs 中执行终端命令。是否有任何有助于访问命令行界面的模块?假设我想运行这个命令code . 或ifconfig 或cd。那么我怎样才能从 nodejs 应用程序中做到这一点呢?
我知道我可以从我的终端运行 nodejs 但我想访问终端并做任何我想做的事情。比如从终端安装其他软件比如执行 'apt install package-name'
【问题讨论】:
标签:
javascript
node.js
terminal
node-modules
【解决方案1】:
因此,您需要的是一种运行系统特定功能的可移植方法。值得庆幸的是,nodejs 有一个模块可以做到这一点,称为 child_process 模块。有关更具体的信息,您可以查看链接的文档,但一个基本示例如下所示:
const { spawn } = require('child_process');
// Here we make the call making sure to list the command first and the arguments as the next parameter in a list
const diff = spawn('diff', ["texta.txt", "textb.txt"])
// We can also log the output of this function with
diff.stdout.on('data', (data) => {
console.log(data.toString());
});
// or we can log the exit code with
diff.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});