Assume that:
dependency-a
depends on dependency-b
dependency-a
invokes the CLI of dependency-b
via ChildProcess.exec()
dependency-a
has been installed to some project sample_project
Then, the following code of dependency-a
is wrong because the OS simply will not find dep-b
utility:
import ChildProcess from "child_process";
ChildProcess.exec(
"dep-b So_comething",
{ encoding: "utf-8" },
(error: ChildProcess.ExecException | null, stdout: string, stderr: string): void => {
// ...
}
);
'dep-b' is not recognized as an internal or external command, operable program or batch file.
OK, how to refer to it correctly? By "node_modules/.bin/dep-b So_comething"
? Afraid it will not work always because dependency-a
and/or dependency-b
may not be installed directly below "sample_project/node_modules"
.
A failsafe way is npx
(npm exec
). For locally installed binary, it's resolved from the hierarchy of node_modules
directories, making it unnecessary to rely on the exact path:
npx -p=dependency-b dep-b So_comething
instead of
dep-b So_comething
Alternatively, entry point of a binary can be seen in bin
section of dependency-b/package.json
, so a script can be executed directly. The exact path of entry script needs to resolved:
let depDir = path.parse(path.resolve('dependency-b/package.json')).dir;
exec(`node "${depDir}/bin_entry_point.js" So_comething`, ...);