How to execute shell commands in Javascript

mxglt

Maxime Guilbert

Posted on September 21, 2021

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! 🍺

💖 💪 🙅 🚩
mxglt
Maxime Guilbert

Posted on September 21, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024