Search code examples
node.jsnpmpackage.jsonnpx

How do I capture arguments from npx commands?


I am trying to capture arguments from npx commands in my code. npx <package-name> <app-name> In the code snippet above, i want to capture the app name when i execute this command. I am passing the npx command in the bin key in the package.json. How do i get the app-name when i run the command?


Solution

  • Assuming your package is a Node.js script (which is usually is), the command line arguments are available in process.argv. If you only care about the first thing (app-name in your example), you can use process.argv[2]. (Element 0 in the array will be the executable name and element 1 will be the module name.) However, if there are command line flags or other arguments, that won't work. Once you're dealing with any complexity or uncertainty, you may want to use an arguments-parsing module like yargs.