Q:

Gradle couldn't execute npm command

I'm trying to run a npm command inside of gradle task but I'm getting a strange error:
Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'npm'
    at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27)
    at net.rubygrapefruit.platform.internal.WrapperProcessLauncher.start(WrapperProcessLauncher.java:36)
    at org.gradle.process.internal.ExecHandleRunner.run(ExecHandleRunner.java:65)
    ... 2 more
Caused by: java.io.IOException: Cannot run program "npm" (in directory "/Users/psilva/Documents/projects/registrolivre"): error=2, No such file or directory
    at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:25)
    ... 4 more
Caused by: java.io.IOException: error=2, No such file or directory

And this is my task:
task npmInstall(type: Exec) {
    commandLine "npm", "install"
}

Could someone help?

A:

This answer worked for me with a different npm-related task.  The recommendation there is to use an executable and args rather than commandLine.
executable 'npm'
args ['install']
 
Depending on your directory structure, you may also need to add the workingDir property and set it to the directory where your package.json lives.
As an alternative, the Gradle Node Plugin is also really handy for managing the most common Node tasks in a Gradle build.  I use this plugin as the basis for my Node tasks and then create other custom tasks as needed.

A:

If you are on Windows try this:
task npmInstall(type: Exec) {
    commandLine "npm.cmd", "install"
}

instead of this:
task npmInstall(type: Exec) {
    commandLine "npm", "install"
}

A:

If you are using Windows OS, you have to use 'npm.cmd' instead of 'npm'. Better to detect whether OS is windows or not and build your npm command. Please see the code snippet below,
import org.apache.tools.ant.taskdefs.condition.Os

task npmInstall(type: Exec) {
    String npm = 'npm';
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        npm = 'npm.cmd'
    }
    workingDir 'src/main/webapp'
    commandLine npm, 'install'
}

