Home > OS >  Calling npx from a node.js file
Calling npx from a node.js file

Time:12-20

I've tried using exec with a bash file, I've tried using direct calls, I've tried digging into npm and npx docs but there seems to be no answer to this question: how can an npx call be triggered form node.js code?

An answer that triggers the same functionality as an npx call without actually being written as an npx call would also be acceptable.

CodePudding user response:

I am not really sure where your problem is...

  • how you call npx scripts in general?
  • running shell commands from within node?
  • Running specifically npx commands? Is there an error you get?

The most widespread way to run shell commands would be child_process, and I don't know why you couldn't just put an npx command in there (I just tested it with npx --help and that worked):

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

exec("echo Hello World", (err, stdout, stderr) => {
  if (err) {
    console.error();
    console.error("Error:");
    console.error(err);
    console.error();
  }
  console.log(stdout);
  console.error(stderr);
});

Now, this might be what you meant by "tried using exec", and you just get an error doing that. Of course, it would be helpful to have that error in that case, but maybe it is that npx isn't found.

Make sure you have npx installed then - maybe it's just npms virutal environment that can't access it, so you could use npm install npx to install it into there. If you are running it with npm, make sure it's installed globally: npm install -g npx.

If it is a different problem, please provide more information on what exactly you are lacking or potential errors you are getting.

  • Related