What is npx and when would you use it instead of npm install?
npx runs a package's command, using a local copy if present or downloading it temporarily. It is good for one-off tools and project generators, so you avoid installing them globally.
Explain it simply
Suppose you need a tool once, like a scaffolding generator that creates a new project. Installing it globally means it sits on your machine, ages, and gets out of date. npx is like hiring a cab for one trip instead of buying a car: it fetches the package, runs the command, and does not leave it installed globally.
Example
# create a project with a generator, always the latest version
npx create-next-app@latest my-site
# run a locally installed binary without an npm script
npx eslint src/
# run a specific version of a tool once
npx typescript@5.4 --versionHow it decides what to run:
- Looks in the local
node_modules/.binfor the command. - If not found, downloads the package into a cache and runs it, asking for confirmation first in recent npm versions.
npx ships with npm, so there is nothing extra to install. It is also handy in CI for tools you do not want in package.json.
What to say in the interview
"npx executes a package binary, preferring the local install and otherwise fetching it temporarily. I use it for generators and one-off tools so I avoid global installs and always get a known version."
Common mistakes
- Thinking npx and npm are unrelated; npx comes bundled with npm.
- Running
npx some-packagewithout checking the package name, which can run unknown code from the internet.