Abhishek Jagwani
Abhishek Jagwani

Reputation: 31

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?

Upvotes: 3

Views: 8206

Answers (3)

TOPKAT
TOPKAT

Reputation: 8698

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

Upvotes: 2

AndoGhevian
AndoGhevian

Reputation: 58

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.

Upvotes: 1

sadrzadehsina
sadrzadehsina

Reputation: 1349

Have a look at this node module.

https://github.com/shelljs/shelljs#examples

Upvotes: 0

Related Questions