[node.js] Print a list of all installed node.js modules

In a node.js script that I'm working on, I want to print all node.js modules (installed using npm) to the command line. How can I do this?

console.log(__filename);

//now I want to print all installed modules to the command line. How can I do this?

This question is related to node.js

The answer is


Why not grab them from dependencies in package.json?

Of course, this will only give you the ones you actually saved, but you should be doing that anyway.

console.log(Object.keys(require('./package.json').dependencies));

Generally, there are two ways to list out installed packages - through the Command Line Interface (CLI) or in your application using the API.

Both commands will print to stdout all the versions of packages that are installed, as well as their dependencies, in a tree-structure.


CLI

npm list

Use the -g (global) flag to list out all globally-installed packages. Use the --depth=0 flag to list out only the top packages and not their dependencies.


API

In your case, you want to run this within your script, so you'd need to use the API. From the docs:

npm.commands.ls(args, [silent,] callback)

In addition to printing to stdout, the data will also be passed into the callback.


for package in `sudo npm -g ls --depth=0 --parseable`; do
    printf "${package##*/}\n";
done

If you are only interested in the packages installed globally without the full TREE then:

npm -g ls --depth=0

or locally (omit -g) :

npm ls --depth=0


list of all globally installed third party modules, write in console:

 npm -g ls

in any os

npm -g list

and thats it