13

I've got a project which happens to have a full node_modules directory, and a package-lock.json file, but no package.json file.

so I ran npm init to create a new package.json file, but now I'm struggling to make it contain the dependecies of the project.

Is there a way to make npm read the node_modules directory or the package-lock.json and create a matching package.json file?

Efrat Levitan
  • 5,181
  • 2
  • 19
  • 40

1 Answers1

16

The package-lock.json does not contain enough information to produce an accurate package.json file. It contains a list of all the package that are installed, and the version, but it also includes sub-dependencies in the list.

You could read the information and create a new dependencies list, but you would end up with a list of all the dependencies, including sub-dependencies you don't directly depend on. There would also be no distinction between dependencies and devDependencies.

Interestingly, npm does seem to be able to remember which packages were installed in a given directory for some amount of time (it's probably cached somewhere). If the lock file was originally created on your machine, a simple npm init might give you an accurate package.json file.

If you really want to produce a list of all the packages in a JSON format, you could use a script like this:

var dependencies = require('./package-lock.json').dependencies;
var list = {};

for (var p of Object.keys(dependencies)) {
    list[p] = dependencies[p].version;
}
console.log(JSON.stringify(list, null, '  '));
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • you are right, there is no official command to produce such a thing, but i need a packagejson file desperatly. do you have any idea for a workaround, such as a script that will list the dependecies for me? – Efrat Levitan Dec 19 '18 at 21:14
  • 1
    @Efrat I added a little script that can list out the dependencies. – Alexander O'Mara Dec 19 '18 at 21:19
  • I don't know what I did. I ran this as "node package-list.js". It worked great! I +1'd the answer. Then, I upgraded npm to 6.14.5. I deleted the incomplete package.json in this project that had only a package-lock.json before I attempted `npm init`. So, that deleted I ran `npm init` again, accepted all the defaults, and my package.json has like 184 packages in "dependencies" now!? Sweird. I've not look at release notes, but maybe this was just introduced? – Neil Gaetano Lindberg Jun 17 '20 at 19:22