Print a list of all installed node.js modules

后端 未结 7 1993
情话喂你
情话喂你 2020-12-22 17:29

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         


        
相关标签:
7条回答
  • 2020-12-22 17:44

    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.

    0 讨论(0)
  • 2020-12-22 17:47

    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

    0 讨论(0)
  • 2020-12-22 17:48

    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));
    
    0 讨论(0)
  • 2020-12-22 17:48
    for package in `sudo npm -g ls --depth=0 --parseable`; do
        printf "${package##*/}\n";
    done
    
    0 讨论(0)
  • 2020-12-22 17:49

    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' }
    
    0 讨论(0)
  • 2020-12-22 18:00

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

     npm -g ls
    
    0 讨论(0)
提交回复
热议问题