Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update node modules programmatically

I need to use the npm update from a script. Below is my code:

var npm = require('npm');
npm.load(function () {
npm.commands.outdated({json: true}, function (err, data) {
    //console.log(data);
    npm.commands.update(function(err, d){
        console.log(d);
    });
   });
});

When I run this script, the modules get updated, but the new versions are not indicated in the package.json.

When I run npm update --save-dev from command line, folders and package.json get updated.

Please suggest how this can be achieved through the script. How can I use --save-dev option through code?

like image 427
Krishnaveni Avatar asked Jun 04 '16 03:06

Krishnaveni


People also ask

Can you use npm to update node?

Use NPM to Update Your Node Version To update Node with NPM, you will install the n package, which will be used to interactively manage node versions on your device.

Can you edit node module files?

You can use patch-package to make and persist changes to node modules. This can be done by first making changes to the package inside node_modules and then running the following command, with <package name> being the name of the package you just made changes to.


2 Answers

You'll need to specify the {save: true} option when loading the config:

npm.load({save: true}, function() {
  // update code
});

Edit:

The 'save-dev' option for the npm.load command does not work. There's an issue about it here: https://github.com/npm/npm/issues/2369.

The work around is to re-install outdated modules:

npm.load({'save-dev': true}, function () {
  npm.commands.outdated(function (err, rawOutdated) {
    var outdated = rawOutdated.map(function (module) {
      return module[1];
    });
    npm.commands.install(outdated, function(err, d) {

    });
   });
});
like image 191
gnerkus Avatar answered Oct 11 '22 22:10

gnerkus


I think the first argument in the npm.commands.update is a list of arguments. I have never used npm programmatically, but looking at their source code I would try the following:

npm.commands.update(['--save-dev'], function(err, d){
    console.log(d);
});

The reference is on this test: https://github.com/npm/npm/blob/master/test/tap/update-save.js#L87

like image 29
filype Avatar answered Oct 11 '22 23:10

filype