Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

npm scripts and npx

An npm script is a terminal command stored in package.json under a short name. Instead of remembering node --watch --env-file=.env src/server.js, you type npm run dev. This way the project's commands are the same for every developer and on the server.

The scripts section

Open package.json and replace the scripts section:

{
  "scripts": {
    "start": "node src/server.js",
    "dev": "node --watch src/server.js"
  }
}

On the left is the script name, on the right the command. The file src/server.js appears in the HTTP chapter; for now you can put app.js there.

Running a script

npm run dev

npm runs the command from the dev field. For the most common names — start and test — the word run can be omitted:

npm start
npm test

npm run without a name prints the list of all scripts in the project.

Scripts see local packages

Inside scripts, programs from packages installed in the project are available. If you install prettier with -D, you can call it by name:

{
  "scripts": {
    "format": "prettier --write src"
  }
}

npm run format formats all files in the src folder. There is no need to install prettier globally — npm finds it in node_modules/.bin.

npx

npx runs a program from a package without a script. If the package is installed in the project, that copy is used; if not, npm downloads it temporarily:

npx prettier --check src
npx cowsay "Hello"

The first command checks formatting, the second downloads the cowsay package and draws a cow saying "Hello". npx is handy for one-off commands and project generators.

Running with node --run

Node.js 22 added node --run. It runs a script from package.json faster than npm, but without some of npm's features:

node --run dev

Common mistake

Your own scripts, other than start and test, cannot be run without the word run:

npm dev
Unknown command: "dev"

Type npm run dev. If the script is still not found, check that you are in the folder that contains package.json.

Thanks for reading!

Donate to the site — we work hard for you.