Indeed, you can use npm programmatically, and this has been indicated in older versions of the documentation. It has since been removed from the official documentation, but still exists with respect to the control source with the following statement:
Although npm can be used programmatically, its API is designed to be used only by the CLI, and there is no guarantee as to its suitability for any other purpose. If you want to use npm to perform a specific task, the safest thing is to invoke the desired npm command with the appropriate arguments.
The semantic version of npm refers to the CLI itself, and not to the core API. The internal API is not guaranteed to remain stable even when the npm version indicates that no changes have been made according to semver.
The source documentation provides an example of the code that was provided:
var npm = require('npm') npm.load(myConfigObject, function (er) { if (er) return handlError(er) npm.commands.install(['some', 'args'], function (er, data) { if (er) return commandFailed(er)
Since npm exists in the node_modules folder, you can use require('npm') to load it like any other module. To install the module, you will want to use npm.commands.install() .
If you need to look at the source, then also on GitHub . Here is a complete working code example that is equivalent to running npm install without command line arguments:
var npm = require('npm'); npm.load(function(err) { // handle errors // install module ffi npm.commands.install(['ffi'], function(er, data) { // log errors or data }); npm.on('log', function(message) { // log installation progress console.log(message); }); });
Note that the first argument to the install function is an array. Each element of the array is a module that will try to install npm.
More advanced usage can be found in the npm-cli.js in the source control.