npm install で「permission denied」となった場合の解決方法



npm install -g xxxでパッケージをインストールしようとすると、権限絡みのエラーが出た。

$ npm i -g gatsby-cli
npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm WARN acorn-dynamic-import@4.0.0 requires a peer of acorn@^6.0.0 but none is installed. You must install peer dependencies yourself.

npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/local/lib/node_modules
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules'
npm ERR! }
npm ERR! 
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR! 
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.



1. Nodeのバージョン管理ツールを使ってnpmを再インストールする



We strongly recommend using a Node version manager to install Node.js and npm. We do not recommend using a Node installer, since the Node installation process installs npm in a directory with local permissions and can cause permissions errors when you run npm packages globally.



2. npmのデフォルトディレクトリを手動で変更する


  1. ホームディレクトリにグローバルインストール用のディレクトリを作成

    $ mkdir ~/.npm-global
  2. 新しいディレクトリパスを使用するようにnpmを構成

    $ npm config set prefix '~/.npm-global'
  3. 任意のテキストエディタで、~/.profileファイルを開くか作成して、次の行を追加

    $ export PATH=~/.npm-global/bin:$PATH
  4. 更新

    $ source ~/.profile