Home > Net >  error relative path global package nodejs
error relative path global package nodejs

Time:11-14

I create a package with several choices and depending on the choice I run a bash script .sh with execFile from node it works fine locally with the path "./utils/myScript.sh

but when I create the package with npm pack and install globally it cannot find the script files in the utils directory. on the other hand if I put the path /usr/local/lib/node_modules/choicescript/utils/myScript.sh it works

how to tell it to use relative path and not absolute path

I have another minor problem when the script this launches I have my log but I do not see the return of the script displayed as if I launched this one directly with ./myScript.sh

const program = require("commander");
const chalk = require("chalk");
const inquirer = require("inquirer");
const { execFile } = require("child_process");

let opts = {
    shell: "/bin/bash",
};

function devFunc() {
    execFile("./utils/myScrypt.sh", opts, (error, stdout, stderr) => {
        log(stdout);
        log(stderr);
        if (error !== null) {
            log(`exec error: ${error}`);
        }
    });

    log(chalk.green.bold("\033[32;5mDATABASE DEV RUN - host: 127.0.0.1 - port: 3306\033[0m - ")   chalk.blue.bold(`CTRL C pour quitter`));
}

const { dev, preprod, prod } = program.opts();
if (dev) {
    devFunc();
} else if (preprod) {
    preprodFunc();
} else if (prod) {
    prodFunc();
} else {
    inquirer
        .prompt([
            {
                type: "rawlist",
                name: "Database_gcp",
                message: "Database choice",
                choices: ["dev", "preprod", "prod", "exit"],
            },
        ])
        .then((gcp) => {
            if (gcp.Database_gcp === "dev") {
                devFunc();
            }
            if (gcp.Database_gcp === "preprod") {
                preprodFunc();
            }
            if (gcp.Database_gcp === "prod") {
                prodFunc();
            }
            if (gcp.Database_gcp === "exit") {
                log(chalk.blue("EXIT"));
            }
        });
}

CodePudding user response:

Instead of doing a relative import/require - you can use the __dirname constant and use "join" for better compatibility. The __dirname yields the full path directory of the current module.

//...
const { join } = require('path');
//...

execFile(join(__dirname, 'utils', 'myScrypt.sh'), opts, (error, stdout, // ...
  • Related