DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

How to execute shell commands in Javascript

Working in Javascript apps, you might have to use shell commands to retrieve some informations or execute some treatments.

So here is the snippet to do it!


Code

const childProcess = require('child_process');

async function sh(cmd_to_execute) {
    return new Promise(function (resolve, reject) {
        childProcess.exec(cmd_to_execute, (err, stdout, stderr) => {
            if (err) {
                reject(err);
            } else {
                resolve({stdout, stderr});
            }
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

You can use this function which will return you the result of the command.


I hope it will help you! 🍺

Top comments (0)