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(__fil
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.
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.
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.
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
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));
for package in `sudo npm -g ls --depth=0 --parseable`; do
printf "${package##*/}\n";
done
Use npm ls (there is even json output)
From the script:
test.js:
function npmls(cb) {
require('child_process').exec('npm ls --json', function(err, stdout, stderr) {
if (err) return cb(err)
cb(null, JSON.parse(stdout));
});
}
npmls(console.log);
run:
> node test.js
null { name: 'x11', version: '0.0.11' }
list of all globally installed third party modules, write in console:
npm -g ls