0

I've created a cli to format my project and install some dependencies.

I try to run

const runNpm = () => {
  return new Promise(resolve => {
    npm.load(function(err) {
      // handle errors

      npm.commands.install(
        ["@angular/core", "@angular/cli --save-dev"],
        function(err, data) {
          if (err) {
            reject(err);
          }
          console.log("dependencies installed");
          resolve();
        }
      );

      npm.on("log", function(message) {
        console.log(message);
      });
    });
  });
};

Without --save-dev it work perfectly
I've searched on internet, but couldn't find nothing.

Raphaël Balet
  • 6,334
  • 6
  • 41
  • 78
  • Out of curiousity, what's the use case for running npm commands withing node.js rather than doing this via package.json? – Qiniso Nov 18 '19 at 09:55
  • @Qiniso I have a cli that format an angular project newly created (Create folder structure, generated base files and update tslint). Because I'm using [tslint-config-standard-plus](https://www.npmjs.com/package/tslint-config-standard-plus) I want my cli to being able to download the required dependencies without having to do anything. It may exist another solution that I'm not aware of in that case, I would be glad to hear it :) – Raphaël Balet Nov 18 '19 at 14:13

2 Answers2

0

You can check the solution here: Can I install a NPM package from javascript running in Node.js? for general npm packages installation using npm package manager from javascript code.

I hope this will help.

Sadmi
  • 311
  • 2
  • 15
  • Thanks for the link. If I understand it right, it isn't possible to do it directly via `npm.commands.[something]` but rather to do it like that. ```shell var exec = require('child_process').exec; child = exec('npm install ffi').stderr.pipe(process.stderr); ```? _thx to [the Vyacheslav answer](https://stackoverflow.com/a/19406194/11135174)_ – Raphaël Balet Nov 18 '19 at 14:15
  • @rbalet I believe you can use the both methods and you will reach the same result. – Sadmi Nov 18 '19 at 14:20
  • do you have a sample for the first method? It's what I'm not able to find.. – Raphaël Balet Nov 18 '19 at 14:32
0

I believe I found the solution that will save the package into the dev list, you have to use npm.load() as follows:

var npm = require('npm');

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

    npm.commands.install(['@angular/core', '@angular/cli'], function (err, data) {
        if (err) return console.error(err)
    });
});

Original answer is here: Programmatically install a npm package, providing --save-dev flag

Sadmi
  • 311
  • 2
  • 15