How to remove sudo requirement for local npm insta

2019-01-27 04:07发布

问题:

I recently updated my npm version to 2.5.1 and when I installed express locally in my project under node_modules using npm install express --save it came up with this error:

npm WARN locking Error: EACCES, open '/Users/patrick/.npm/_locks/express-44e9a2fe3cb5b729.lock'
npm WARN locking     at Error (native)
npm WARN locking  /Users/patrick/.npm/_locks/express-44e9a2fe3cb5b729.lock failed { [Error: EACCES, open '/Users/patrick/.npm/_locks/express-44e9a2fe3cb5b729.lock']
npm WARN locking   errno: -13,
npm WARN locking   code: 'EACCES',
npm WARN locking   path: '/Users/patrick/.npm/_locks/express-44e9a2fe3cb5b729.lock' }
npm ERR! Darwin 13.4.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "express" "--save"
npm ERR! node v0.12.0
npm ERR! npm  v2.5.1

npm ERR! Attempt to unlock (path to project here)/node_modules/express, which hasn't been locked

When I ran it again with sudo it worked fine, but now my text editor requires me to type in my password every time I overwrite files in the project folder. Why is this happening and how do I fix it?

Note, I not only want to prevent local installs from requiring sudo, but I also want to unlock the project folder so I don't have to keep typing in my password in the text editor.

回答1:

Doing sudo npm is not recommended by the npm creator Isaac Schlueter:

I strongly encourage you not to do package management with sudo! Packages can run arbitrary scripts, which makes sudoing a package manager command as safe as a chainsaw haircut. Sure, it’s fast and definitely going to cut through any obstacles, but you might actually want that obstacle to stay there.

You shouldn't need it ever with correct permissions and ownership settings:

chown -R $USER <directory>

See here for more details.

Even after, if you run sudo npm again, every created subdirectory will be owned by the superuser and you will be getting errors whenever trying to access them as normal user.

So resist the sudo temptation :)



回答2:

I went into ~/.npm and ran sudo rm -R ./* to delete the cache, then I modified the permission of the project folder back to my user by running cd (path to project) and sudo chmod -R patrick ./*