Problem using child-process vs terminal while executing a command

I try to execute a command using a child-process and I can’t execute by absolute path using nodejs, but when I use terminal, everything is fine.

Why is that?

My code is right here:

const cp = require('child_process');

const commandExecutor = 'node-install/target/node/yarn/dist/bin/yarn.exe';
const symlinkFolder = 'node-install/target/node/target/symlink';

const workingDirectories = [];

Array.from(process.argv).forEach((value, index) => {
  if (index >= 2) {
    workingDirectories[index - 2] = value;
  }
});

workingDirectories.forEach(function(workingDirectory) {
  const argumentsUnlink = 'unlink @item@ --link-folder ' + symlinkFolder + ' --cwd ' + workingDirectory;
  const unlinkCommand = commandExecutor + ' ' + argumentsUnlink;

  const execution = cp.exec(
      unlinkCommand,
      function (error, stdout, stderr) {
        console.log(stdout);
        console.log(error);
        console.log(stderr);
      });
  execution.on('exit', function (code) {
    let message = 'Child process exited with exit code ' + code + ' on route ' + workingDirectory;
    console.log(message);
  });
});

An example of command is:

node-install/target/node/yarn/dist/bin/yarn.exe unlink @item@ --link-folder node-install/target/node/target/symlink --cwd appointments/target/generated-sources/frontend/

But the error I’ve got is:

'node-install' is not recognized as an internal or external command, operable program or batch file.
While I execute command from terminal, everything is fine.

>Solution :

One of the possible problems – NodeJs unable to locate the file by relative path. You can use construct absolute path to fix this, few options to help if node-install is located in your project root (not ultimate list):

  • __dirname, which returns the directory of current module, so if
node-install/../..
index.js

then in index.js we can use

const commandExecutor = `${__dirname}/node-install/target/node/yarn/dist/bin/yarn.exe`;
  • process.cwd(), which returns full path of the process root, so if you start nodejs from folder having node-install, then you can refer to exe like this:
const commandExecutor = `${process.cwd()}/node-install/target/node/yarn/dist/bin/yarn.exe`;

Leave a Reply