npm throws error without sudo

前端 未结 30 2405
清酒与你
清酒与你 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条回答
  •  萌比男神i
    2020-11-21 08:00

    Other answers are suggesting to change ownerships or permissions of system directories to a specific user. I highly disadvise from doing so, this can become very awkward and might mess up the entire system!

    Here is a more generic and safer approach that supports multi-user as well.

    Create a new group for node-users and add the required users to this group. Then set the ownership of node-dependant files/directories to this group.

    # Create new group
    sudo groupadd nodegrp 
    
    # Add user to group (logname is a variable and gets replaced by the currently logged in user)
    sudo usermod -a -G nodegrp `logname`
    
    # Instant access to group without re-login
    newgrp nodegrp
    
    # Check group - nodegrp should be listed as well now
    groups
    
    # Change group of node_modules, node, npm to new group 
    sudo chgrp -R nodegrp /usr/lib/node_modules/
    sudo chgrp nodegrp /usr/bin/node
    sudo chgrp nodegrp /usr/bin/npm
    
    # (You may want to change a couple of more files (like grunt etc) in your /usr/bin/ directory.)
    

    Now you can easily install your modules as user

    npm install -g generator-angular
    

    Some modules (grunt, bower, yo etc.) will still need to be installed as root. This is because they create symlinks in /user/bin/.

    Edit

    3 years later I'd recommend to use Node Version Manager. It safes you a lot of time and trouble.

提交回复
热议问题