Home > Net >  Invoke packaged bash script from Node.js CLI using commander.js
Invoke packaged bash script from Node.js CLI using commander.js

Time:04-21

I am trying to write a CLI with commander.js. I want to have a certain command in the CLI invoke a previously written bash script, as well as pass arguments to it. I know I can use shell.exec() for this like so inside "index.js":

shellCommand = `./RunScripts/bashScript.sh ${options.option1} ${options.option2}`;
if (shell.exec(shellCommand).code !== 0) {
    // ...do things
}

This means I need to include the bash script with my package when I publish the CLI. Using npm pack --dry-run, I can see that the scripts do get included with the package. Here's a rough outline of the file system I have here:

├── my-cli-directory
│   ├── README.md
│   └── RunScripts
│      └── bashScript.sh
│   ├── package.json
│   └── index.js

When I publish my CLI and try to download it with npm install ... it gives me an error message that looks like this:

/bin/sh: ./RunScripts/bashScript.sh: No such file or directory

This would make sense, as I am trying to tell shell.exec to run something that should be available at that location. Instead, how do I tell shell.exec to run the script packaged with my CLI?

CodePudding user response:

I was able to solve this by changing how I reference the location of the bash script.

Instead of:

shellCommand = `./RunScripts/bashScript.sh ${options.option1} ${options.option2}`;

I ran:

shellCommand = `${__dirname}/RunScripts/bashScript.sh ${options.option1} ${options.option2}`;

I'd totally forgotten about the __dirname variable.

  • Related