npm Community Forum (Archive)

The npm community forum has been discontinued.

To discuss usage of npm, visit the GitHub Support Community.

How do I use npm api programatically?

Here’s what I tried so far

var npm = require('npm');

npm.load(() => {
    npm.config.set('dry-run', true);
    npm.config.set('audit', false);
    npm.config.set('package-lock', false);
    var where = '/tmp/example';
    var args = ['copee'];
    npm.install(where, args);
});

But I get the error

TypeError [ERR_INVALID_ARG_TYPE]: The “path” argument must be of type string. Received type object

How do I use the npm api programatically to install a package to a specified directory?


Using npm directly as an api is not supported, and will change without warning in the near future.

The best way to use it programmatically is to use libnpm or, if that’s not supported yet (such as your example), invoke npm using child_process.spawn or a similar tool.


The use of yet makes me think that you will eventually support this behavior in libnpm?

I am currently using the child process spawn feature but that will not work when bundling runtime dependencies, such as ncc.

How often is this private API changing? I don’t mind pinning to a specific version of npm and fixing each release.


Yep. Eventually, the npm CLI is going to be a thin UI layer on top of libnpm

You can do what you want, but I’m not going to answer questions about it. That’s what “unsupported” means.


How is it planned to work with tink? Would, say, tink shell have an equivalent libnpm.shell(file, options)?

Edit: and things like config loading, would that be considered UI?


Yep, just like that! :slight_smile:

There’s already libnpm.config.read()!