3

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?

4
  • 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. Commented 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? Commented 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. Commented Dec 3, 2018 at 16:36
  • Thank you for the reference Commented Dec 3, 2018 at 16:38

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, is there any way to send another command after the first one?
@HolyRandom yes sure, see the last example
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.

Comments

0

Have a look at this node module.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.