The problem:

If you are using mac and install nodejs via pkg file downloaded from the official website, you are likely to encounter this error message when you try to install a npm module globally:

npm ERR! Please try running this command again as root/Administrator.

My solution

DO NOT use sudo command to install the package!

sudo npm install module -g

Some people suggest the above solution on Stack Overflow, but I strongly encourage you not to do package management with sudo. This hack may temporarily solve your problem, but you will encounter more problems later on.

Here is the recommanded way:

Step 1: Find out your username with this command:

whoami

For example, my username is victorleungtw

Step 2: Change ownership of the node modules folder:

sudo chown -R `whoami` /usr/local/lib/node_modules

Then you won’t ever have to use sudo when you install npm packages.


Originally published at victorleungtw.com on February 20, 2015.