Running Commands from Command-line

Sometimes it is necessary to run commands from the command-line, because the plugin might not yet do what you require, or you just want to test something arbitrarily. The good news is that you don’t have to have separate installation for this. With the org.ysb33r.nodejs.cmdline plugin you can run node, npm and npx via Gradle and pass all the required arguments. By default, this will execute in the NPM home directory.

$ ./gradlew node '--args=--check app/index.js' (1)
$ ./gradlew node --arg=--check' --arg app/index.js (2)
$ ./gradlew npm --args=version (3)
$ ./gradlew npx --args=gulp (4)
1 Run node using --args which accept a list of arguments that are space separated. Not the use of quotes to prevent shell escaping.
2 Run node using multiple --arg options. Each one will be added to the node command-line.
3 Run npm. Both --args and --arg can be used.
4 Run npx. Both --args and --arg can be used.

Customising the command-line

Environmental settings for these commands are controlled from the nodejs and npm project extensions. In the case of npm and npx the npm_config_userconfig and npm_config_globalconfig environmental variables will be set. This configuration should be sufficient for most cases, but should you feel the need to customise you have the following options available from the tasks.

environmentProvider

This setter takes a provider of Map<String,Object> which will set the environment for the command, rather than reading it from

workingDir

This setter take anything than can be converted to File and is then used instead of the npm.homeDirectory setting.

tasks.node { (1)
    workingDir = projectDir (2)
}
1 Works the same for npm and npx. Due to the presence of the npm extension, using tasks.npm will be needed in the Groovy DSL.
2 Override working directory.

Using Wrappers

If the above solutions are not sufficient for you, consider generating wrappers into your project. These wrappers will use the version of node specified in the project’s nodejs extension. They can be checked into your source repository.

Benefits
  • You can run any of these like you would run the original binaries, and they would use the versions tied to your project. As such everyone in your team are using the correct versions.

  • You can also update your IDE to use these wrappers instead of using the global installed ones.

  • You don’t have to fiddle with nvm or remember which version to switch to.

Usage
plugins {
  id 'org.ysb33r.nodejs.wrapper' version '{revnumber}'
}

Now just run ./gradlew nodeWrappers.