DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

5 1

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)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay