How/why does npm recommend not running as root?

前端 未结 3 1554
说谎
说谎 2020-11-30 19:43

In short...

First of all, why does npm suggest that it should only run as non-root? I highly disbelieve that every other package manager (apt, y

3条回答
  •  青春惊慌失措
    2020-11-30 19:57

    The simple answer is web servers should never be run as root for well known security reasons, so this goes for npm commands as well.

    To start fresh, remove prior Node.js and npm installs as well as these files/directories:

    mv ~/.npmrc       ~/.npmrc~prior
    mv ~/.npm         ~/.npm~prior
    mv ~/tmp          ~/tmp.~prior
    mv ~/.npm-init.js ~/.npm-init.js~prior
    

    Solution: Install Node.js (which comes with npm) as NON root (no sudo)

    Download Source Code directly from https://nodejs.org/en/download/

    Execute the below as yourself (Linux/OS X)

    cd node-v8.1.2  # into expanded source dir
    
    export NODE_PARENT=${HOME}/node-v8.1.2 # put this into your ~/.bashrc
    

    Feel free to change above export to whatever location is appropriate

    ./configure   --prefix=${NODE_PARENT}
    make -j4   # for dual core ... use  -j8  for quad core CPU
    make install
    

    which puts the binaries for Node.js and npm as well as its modules repository into $NODE_PARENT, a $USER owned dir which then allows you to issue subsequent npm install xxx commands as yourself.

    To reach the binaries for node and npm alter your PATH environment variables in your ~/.bashrc:

    export PATH=${NODE_PARENT}/bin:${PATH}
    export NODE_PATH=${NODE_PARENT}/lib/node_modules
    

    Then to install packages into that directory (global), as opposed to the current directory (local) always pass in the -g flag (global):

    npm install -g someModule
    

    NOTE - at no time are you executing anything npm or node related as root / sudo.

提交回复
热议问题