🙌

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

2021/05/05に公開

エラーの内容

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.

解決法

公式には2つの解決方法が紹介されている。

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

公式ではこちらのやり方が推奨されている。

今回は別のやり方(次項参照)で解決してしまったが、nnvmといったバージョン管理ツールを使って再インストールすることで解決できた気がする。
というのも、公式に次のようなことが書かれていた。

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.

インストーラを使った場合、ローカルの権限を持つディレクトリにnpmがインストールされるため、パッケージをグローバルに実行すると権限エラーが発生する可能性がある」、と書かれてある。

Nodeのバージョン管理ツールを使わず、公式からインストーラをダウンロードしてインストールしていたのが問題だったと思われる。

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

今回はこちらの方法で解決した。
Windowsでは使えないらしい。

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

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

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

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

    $ source ~/.profile
    

Discussion