How to execute local bash code from VSCode extensi

2020-03-31 04:05发布

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?

1条回答
聊天终结者
2楼-- · 2020-03-31 05:00

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.
}
查看更多
登录 后发表回答