Ubuntu – Command not found when executing node.js n package on sudo

14.04nodejs

I'm trying to update my version of node to the latest stable.

Using this resource I was able to:

sudo npm install n -g

But when I try

sudo npm n stable

I get:

sudo: n: command not found

If I run n stable, the command is present:

n stable
mkdir: cannot create directory ‘/usr/local/n’: Permission denied
mkdir: cannot create directory ‘/usr/local/n’: Permission denied
mkdir: cannot create directory ‘/usr/local/n’: Permission denied
mkdir: cannot create directory ‘/usr/local/n’: Permission denied

     install : node-v0.12.2
       mkdir : /usr/local/n/versions/node/0.12.2
mkdir: cannot create directory ‘/usr/local/n’: Permission denied

  Error: sudo required

Best Answer

Surprisingly, your npm installation has the global prefix in a folder called npm on your home directory, this means that any package installed with the -g flag will install on this folder.

You can change this folder to any folder that is on the sudo safe path following these steps:


Graphical way:

  1. Open a File Manager (a.k.a Nautilus).
  2. Navigate to your home folder.
  3. Press Ctrl+H to show hidden files.
  4. Open a file called .npmrc with your favorite text editor.
  5. Find a line on that file with this content:

    prefix=/home/<your_username>/npm
    
  6. Replace /home/<your_username>/npm by a safe path (such as /usr/local/bin).
  7. Once replaced it will look like this:

    prefix=/usr/local/bin
    
  8. Save the file.
  9. Run again sudo npm install n -g

Terminal way:

Run this command:

sed -i.bak "s%^prefix=.*$%prefix=/usr/local/bin%" ~/.npmrc
Related Question