GitHub @actions/exec
Published Mon Feb 05 2024Today I learned about GitHub’s @actions/exec package. This allows you to execute shell commands from JavaScript in a GitHub action! There are 2 methods to use, the one I needed was not in the README example for this library.
exec.exec
First is exec.exec
. This method runs the provided command, returning a Promise that resolves once the command has finished running.
const exec = require('@actions/exec');
await exec.exec('nu', ['my-script.nu']);
When you need the output of the executed command this example code is provided:
const exec = require('@actions/exec');
let myOutput = '';
let myError = '';
const options = {};
options.listeners = {
stdout: (data: Buffer) => {
myOutput += data.toString();
},
stderr: (data: Buffer) => {
myError += data.toString();
}
};
options.cwd = './lib';
await exec.exec('nu', ['my-script.nu'], options);
This setup with options.listeners
to collect stdout
and stderr
is not all needed. The library includes an additional helper named getExecOutput
that includes this bit of code for you. This was not as visible in the documentation as it should be since getting output is likely a common use case.
const { stdout } = await exec.getExecOutput('nu', ['my-script.nu']);
The GitHub actions toolkit is very conveniently set up. I have liked using this @actions/exec
package.