npm install -g 〇〇に失敗する

エラー内容

権限がないと言われているようです

% npm install -g typescript
npm ERR! code EACCES
npm ERR! syscall mkdir
npm ERR! path /usr/local/lib/node_modules/typescript
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/typescript'
npm ERR!  [Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/typescript'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: '/usr/local/lib/node_modules/typescript'
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.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/your-directory/.npm/_logs/2022-05-28T05_07_04_914Z-debug.log
(base) [ディレクトリ名] % npm install -g npm       

npm ERR! code EACCES
npm ERR! syscall rename
npm ERR! path /usr/local/lib/node_modules/npm

解決方法

npmのデフォルトディレクトリを作成する。

$ mkdir ~/.npm-global
$ npm config set prefix '~/.npm-global'
$ echo ' export PATH=~/.npm-global/bin:$PATH' >> ~/.bash_profile
$ source ~/.bash_profile

パッケージのインストールに成功するようになった。

% npm install -g npm

added 1 package, and audited 202 packages in 4s

11 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
% npm install -g typescript

added 1 package, and audited 2 packages in 3s

found 0 vulnerabilities

参考

【備忘録】npm -g install に失敗する - Qiita