npm throws error without sudo

前端 未结 30 1988
清酒与你
清酒与你 2020-11-21 07:43

I just installed node and npm through the package on nodejs.org and whenever I try to search or install something with npm it throws the following error, unless I sudo the c

30条回答
  •  别那么骄傲
    2020-11-21 07:58

    Permissions you used when installing Node will be required when doing things like writing in your npm directory (npm link, npm install -g, etc.).

    You probably ran node installation with root permissions, that's why the global package installation is asking you to be root.


    Solution 1: NVM

    Don't hack with permissions, install node the right way.

    On a development machine, you should not install and run node with root permissions, otherwise things like npm link, npm install -g will need the same permissions.

    NVM (Node Version Manager) allows you to install Node without root permissions and also allows you to install many versions of Node to play easily with them.. Perfect for development.

    1. Uninstall Node (root permission will probably be required). This might help you.
    2. Then install NVM following instructions on this page.
    3. Install Node via NVM: nvm install node

    Now npm link, npm install -g will no longer require you to be root.

    Edit: See also https://docs.npmjs.com/getting-started/fixing-npm-permissions


    Solution 2: Install with webi

    webi fetches the official node package from the node release API. It does not require a package manager, does not require sudo or root access, and will not change any system permissions.

    curl -s https://webinstall.dev/node | bash
    

    Or, on Windows 10:

    curl.exe -sA "MS" https://webinstall.dev/node | powershell
    

    Like nvm, you can easily switch node versions:

    webi node@v12
    

    Unlike nvm (or Solution 3 below), the npm packages will be separate (you will need to re-install when you switch node versions).

    Without changing npm configuration, you can install globally:

    npm install -g prettier
    

    This solution is essentially an automated version of other solutions that install to $HOME.


    Solution 3: Install packages globally for a given user

    Don't hack with permissions, install npm packages globally the right way.

    If you are on OSX or Linux, you can create a user dedicated directory for your global package and setup npm and node to know how to find globally installed packages.

    Check out this great article for step by step instructions on installing npm modules globally without sudo.

    See also: npm's documentation on Fixing npm permissions.

提交回复
热议问题