0

How can I save all the installed node modules in package.json without reinstalling them?

I have something like npm init --yes but, I'm not kinda sure if that works.

Thanks for the help!

Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43

1 Answers1

1

I think there is no way to get that stuff with some inbuilt modules

But you can write your own code to get that info and update in in your own package.json file

var fs = require("fs");

function getPackageInfo() {
  fs.readdir("./node_modules", function(err, module) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(module)
    module.forEach(function(dir) {
      if (dir.indexOf(".") !== 0) {
        var packageFile = "./node_modules/" + dir + "/package.json";
        if (fs.existsSync(packageFile)) {
          fs.readFile(packageFile, function(err, data) {
            if (err) {
              console.log(err);
            } else {
              var json = JSON.parse(data);
              console.log('"' + json.name + '": "' + json.version + '",');
            }
          });
        }
      }
    });

  });
}

getPackageInfo();

Output

"setprototypeof": "1.0.1",
"raw-body": "2.1.7",
"source-map": "0.4.4",
"statuses": "1.3.0",
"transformers": "2.1.0",
"type-is": "1.6.13",
"methods": "1.1.2",
"uglify-js": "2.7.3",
"uglify-to-browserify": "1.0.2",
"utils-merge": "1.0.0",
"unpipe": "1.0.0",
"vary": "1.0.1",
"void-elements": "2.0.1",
"with": "4.0.3",
"window-size": "0.1.0",
"wordwrap": "0.0.3",
"yargs": "3.10.0",
"mime-db": "1.24.0",
...................
..................
..................
.................

You can also use

npm list --depth=0

command to get packages list and version by child_process spawn

abdulbarik
  • 6,101
  • 5
  • 38
  • 59
  • This solution is good as a workaround as there no direct method available. But this might be problematic as npm now (newer versions >= v3) creates flat tree and as a result this code would generate a larger dependency tree then actual. – Pankaj Oct 14 '16 at 05:29
  • u can also use `npm list --depth=0` command to get packages list and version using *shelljs* or *child_process spawn* instead of folder and file traversing – Harpreet Singh Oct 14 '16 at 06:01
  • Do agree, still we need to do some stuff to get it done. But your point is correct I am updating my answer – abdulbarik Oct 14 '16 at 06:07
  • But what I want to do is write all the node modules via npm command line that are not written in package.json... This solution doesn't answer my question, but thank you. – Daniel Gallego Sierra Oct 15 '16 at 05:19