4

It's not very well documented, but you can use npm as a Node.js module and call commands in the code.

I want to capture user input for what packages are required and installing them this way and also save them to the package with the --save-dev flag. I've tried to no avail to get this up and running in code, with it installing but can't find a way to get it to save to the package file.

Is this even possible, or would it have be done another way. Alternate methods are welcome and appreciated.

var npm = require("npm")

npm.load({}, function (er) {
  if (er) return handlError(er)

  npm.commands.install(["titlecase"], function (err, data) {
    if (err) return console.error(err)
  })

})
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177

1 Answers1

8

It is possible, flags need to be passed to npm.load():

var npm = require('npm');

npm.load({ 'save-dev': true }, function (err) {
    if (err) console.log(err);

    npm.commands.install(['lodash'], function (err, data) {
        if (err) return console.error(err)
    });
});

You have the list of flags and their type here.

Wes H
  • 587
  • 3
  • 7
  • 16
Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • As for 2022 this solution doesn't work anymore, npm >8.0.0 deprecated programmatic API, therefore `var npm = require("npm");` inside the project is no longer possible. – Sorin GFS Jun 24 '22 at 07:51