'What does npm run do?

The command npm run will run the command which I set in the package.json, and I think it does not new a child process to run the command. What does npm do to run the command without new a child process?



Solution 1:[1]

Npm run has nothing to do with the node child process if that is what you are asking. Npm run is a command provided by npm CLI which allows to instantiate a shell and execute the command provided in the package.json file of your project.

Considering this is your package.json :

{
  "name": "my-awesome-package",
  "version": "1.0.0",
  "script" : { "test" : "mocha ./test/unit/mytest.js" }
}

Now if you execute npm run test, npm will simply go and check in package.json script section for 'test' key and execute that command in shell or cmd.exe based on your operating system.

If you have not installed mocha globally the command will show error in the console itself, OR if the file mytest.js does not exist the CLI will throw an error which is similar to just typing mocha ./tests/unit/mytest.json

This paragraph from the npm docs which is pretty self-explanatory.

The actual shell your script is run within is platform dependent. By default, on Unix-like systems it is the /bin/sh command, on Windows it is the cmd.exe. The actual shell referred to by /bin/sh also depends on the system. As of [email protected], you can customize the shell with the script-shell configuration.


Update : As per the response in comment, if you want to execute CLI commands via. node without using child_process api you can try exec or execsync(cmd) as a simple workround.This will simply execute your shell cmd and return to your code if no errors were found.

Solution 2:[2]

I want to add an answer since the accepted one is outdated for npm v8.

run, rum and urn are aliases for run-script.

What npm run X does is to run the command under the key X inside scripts object.

If the command to run isn't installed globally, it will search on node_modules because npm adds to the OS PATH node_modules.

So, an example:

`npm run test`

If in package.json we have:

"scripts": {
    "test": "jest --runInBand",

The npm will try to execute the globally installed jest command. And if it's not globally, then it will search on node_modules.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 pmiranda