Export import npm global packages

tl;dr

# Export
npm list --global --parseable --depth=0 | sed '1d' | awk '{gsub(/\/.*\//,"",$1); print}' > path/to/npmfile

# Import
xargs npm install --global < path/to/npmfile

Explanation

Even though the accepted answer gives a pointer, but it does not clearly show how to export/import the global NPM packages.

The output of a simple npm list is very hard to parse:

$ npm list --global --depth=0

/usr/local/lib
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

There are 3 problems with this output:

  1. The first line is not a package name
  2. Those └── are making it hard to parse
  3. Versions are not desirable (at least in my case)

Fortunately, NPM devs were thoughtful enough to include a --parseable option:

$ npm list --global --depth=0 --parseable

/usr/local/lib
/usr/local/lib/node_modules/api-designer
/usr/local/lib/node_modules/bower
/usr/local/lib/node_modules/browserify
/usr/local/lib/node_modules/grunt
/usr/local/lib/node_modules/gulp
/usr/local/lib/node_modules/kong-dashboard
/usr/local/lib/node_modules/npm
/usr/local/lib/node_modules/typescript
/usr/local/lib/node_modules/vue-cli
/usr/local/lib/node_modules/webpack
/usr/local/lib/node_modules/webpack-dev-server
/usr/local/lib/node_modules/yo

Now, the problems are:

  1. The first line does not end with a package name as others do
  2. Path prefixes before the package name (/usr/local/lib/node_modules/)

If we pipe the output to sed '1d', we get rid of that first line. Then we can drop the path prefixes by piping the output to awk to get a clean list of installed package names.

$ npm list --global --parseable --depth=0 | sed '1d' | awk '{gsub(/\/.*\//,"",$1); print}'

api-designer
bower
browserify
grunt
gulp
kong-dashboard
npm
typescript
vue-cli
webpack
webpack-dev-server
yo

You can simply append a > /path/to/file to save the output into the file. Then to install the latest versions of those packages:

xargs npm install --global < path/to/file

You can safely drop the --global arg, to import/export the locally installed npm packages.


npm ls -g --depth=0

Will give you the list of the modules (and their versions) you have installed globally. From the output, you'll be able to generate the npm install command you'll need (depending on if you wan't to keep the versions / your OS ...)


I use this on Windows with PowerShell:

[string]::join(" ", ((npm ls -g --depth=0) | select -skip 1 | select -skiplast 1 | % { $_.remove(0,4) }))

Tags:

Npm