Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Terminal and execute CLI commands via JS / NodeJS

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?

like image 383
Abhishek Jagwani Avatar asked Feb 19 '26 04:02

Abhishek Jagwani


2 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
like image 87
TOPKAT Avatar answered Feb 21 '26 16:02

TOPKAT


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.
like image 34
AndoGhevian Avatar answered Feb 21 '26 16:02

AndoGhevian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!