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?
-
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– Billy Brown2018-12-03 16:29:13 +00:00Commented Dec 3, 2018 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– Abhishek Jagwani2018-12-03 16:34:22 +00:00Commented Dec 3, 2018 at 16:34
-
Yes: from Node JS you can call shell commands answer here and another here. The basic idea is to open a new process and run a command in it.Billy Brown– Billy Brown2018-12-03 16:36:41 +00:00Commented Dec 3, 2018 at 16:36
-
Thank you for the referenceAbhishek Jagwani– Abhishek Jagwani2018-12-03 16:38:00 +00:00Commented Dec 3, 2018 at 16:38
Add a comment
|
3 Answers
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
2 Comments
HolyRandom
Hi, is there any way to send another command after the first one?
TOPKAT
@HolyRandom yes sure, see the last example
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.