1

After seeing this post and other resources, I wanted to try using NPM programmatically so simply I tried:

const npm = require('npm');

but I run into an error of Error: Cannot find module 'npm'.

I did some research and all I saw was to try running npm install npm@latest -g which just updates NPM if I'm not mistaken but I ran it anyways and no change. NPM is already installed globally and I did try installing it locally which got rid of the error but broke the rest of my project so I assume there's a reason that wasn't recommended.

All of the posts I've seen have been older so is this not supported anymore? All the documentation I can find is about the cli and not using it as a module.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mr.Smithyyy
  • 2,157
  • 12
  • 49
  • 95
  • Npm does not have an exposed stable API. Even if you will be able to use it you will rely on something that is unsupported. The only API you can be sure about is CLI, so you can call it in e.g. child process – smnbbrv Mar 05 '19 at 12:58

1 Answers1

0

Use

$ npm i npm

without the global -g Flag


Note: The NPM API is not intended for external use (even tho it is somewhat documented). The problem is, the NPM API does not guarantee stability. In fact, it doesn't even follow semantic versioning. An update to the NPM API is likely to break your script if you heavily rely on it.

If you want to use NPM externally, it would be better to use it as it is right now: a command-line program.

NullDev
  • 6,739
  • 4
  • 30
  • 54