Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute local bash code from VSCode extension

I am creating an extension for simple git commands, and when a user enters a command in the Command Palette, like Init, I want to call git init on their current directory.

Unfortunately, there is no documentation on executing code locally with the VSCode extensions API. Is there any way to do this?

like image 778
Ken Mueller Avatar asked Nov 26 '25 19:11

Ken Mueller


1 Answers

Yes, this is possible, by using child_process.spawn. I have used it in my extension to run a Java jar. The core of the execution is shown here:

let spawnOptions = { cwd: options.baseDir ? options.baseDir : undefined };
let java = child_process.spawn("java", parameters, spawnOptions);

let buffer = "";
java.stderr.on("data", (data) => {
    let text = data.toString();
    if (text.startsWith("Picked up _JAVA_OPTIONS:")) {
        let endOfInfo = text.indexOf("\n");
        if (endOfInfo == -1) {
            text = "";
        } else {
            text = text.substr(endOfInfo + 1, text.length);
        }
    }

    if (text.length > 0) {
        buffer += "\n" + text;
    }
});

java.on("close", (code) => {
    // Handle the result + errors (i.e. the text in "buffer") here.
}
like image 133
Mike Lischke Avatar answered Nov 29 '25 11:11

Mike Lischke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!