user15349738
user15349738

Reputation:

Running Shell Script From Any Directory | NodeJs

I've come across an issue that I can't seem to fix. Take a look at the following snippet. I'm trying to get a shell script running to retrieve some data inside my CLI project. The issue at hand is that it fails to work in any directory other than the specified path meaning that it's a massive inconvenience for not only its users, but myself. So, is there a way to make this code work regardless of the user's current directory? I've looked at some other StackOverflow questions, but I'm not exactly sure I understand how it all works.

example.js

const {exec} = require('child_process');

exec(`sh ./worker/lib/scripts/hi.sh`,
(error, out) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    else if (out) {
        console.log(`stderr: ${out}`);
        return;
    }
});

hi.sh

echo "hi"

Upvotes: 0

Views: 1053

Answers (2)

Refaat
Refaat

Reputation: 1

Another way of handling scripts in a different folder:

exec(`sh ${path.join("worker", "lib", "scripts", "hi.sh")}`)

Upvotes: 0

Orestis Rodriguez
Orestis Rodriguez

Reputation: 21

This is because the path in your command is relative to where you invoke it. Use __dirname instead to get the absolute path of the directory where your executed file is located.

exec(`sh ${__dirname}/worker/lib/scripts/hi.sh`)

Upvotes: 1

Related Questions