Is there any way/code snippet through which we can open Ubuntu terminal and execute terminal commands through JavaScript / Node.js or any UI based language?
Asked
Active
Viewed 6,555 times
3
-
Could you elaborate on your request? Do you mean that from JavaScript, is there a command to open a terminal window? Or is there a way -- from any language -- to open a terminal window? Or perhaps you mean to run shell commands, without necessarily opening a terminal window? From Node.js or other programs with access to OS processes, the answer is yes. From JavaScript in the browser, the answer is no. – Billy Brown Dec 03 '18 at 16:29
-
So i need to build a UI and based on UI input parameters, I need to run I need to perform terminal based commands/shell commands. Is there a way to perform it? – Abhishek Jagwani Dec 03 '18 at 16:34
-
Yes: from Node JS you can call shell commands [answer here](https://stackoverflow.com/questions/14458508/node-js-shell-command-execution) and [another here](https://stackoverflow.com/questions/20643470/execute-a-command-line-binary-with-node-js). The basic idea is to open a new process and run a command in it. – Billy Brown Dec 03 '18 at 16:36
-
Thank you for the reference – Abhishek Jagwani Dec 03 '18 at 16:38
3 Answers
2
You can run any shell command from nodeJs via the childProcess native API (witout installing any dependencies)
Simple way
var { exec } = require('child_process'); // native in nodeJs
const childProcess = exec('git pull');
Snippet to handle logs and errors
I often have a bunch of cli commands to process, so I've created this simple helper. It handle errors, exit and can be awaited in your scripts to match different scenarios
async function execWaitForOutput(command, execOptions = {}) {
return new Promise((resolve, reject) => {
const childProcess = exec(command, execOptions);
// stream process output to console
childProcess.stderr.on('data', data => console.error(data));
childProcess.stdout.on('data', data => console.log(data));
// handle exit
childProcess.on('exit', () => resolve());
childProcess.on('close', () => resolve());
// handle errors
childProcess.on('error', error => reject(error));
})
}
That I can use like:
await execWaitForOutput('git pull');
// then
await execWaitForOutput('git pull origin master');
// ...etc

TOPKAT
- 6,667
- 2
- 44
- 72
1
You can use this module - OpenTerm. It opens new Virtual Terminal in cross platform way and execute command:
const { VTexec } = require('open-term')
VTexec('help') // Runs "help" command.

AndoGhevian
- 58
- 1
- 4