Npm install failed with “cannot run in wd”

Jaxu發表於2016-09-12

  Linux環境下,root賬戶,安裝某些npm包的時候報下面的錯誤,例如安裝grunt-contrib-imagemin時:

Error: EACCES, mkdir '/usr/local/lib/node_modules/coffee-script'
npm ERR!  { [Error: EACCES, mkdir '/usr/local/lib/node_modules/coffee-script']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/coffee-script',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/coffee-script',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack: 
npm ERR!    [ 'DirWriter._create                 (/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23)',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:37:53',
npm ERR!      'Object.oncomplete (fs.js:297:15)' ] }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

  解決辦法如下:

  1. 執行npm install命令時加上--unsafe-perm選項:
    [sudo] npm install --unsafe-perm
  2. 或者將unsafe-perm選項新增到package.json檔案中:
    "config": {
        "unsafe-perm":true
    }
  3. 不要使用preinstall指令碼來安裝全域性模組,你可以單獨安裝它們然後在非root賬戶下安裝其它模組,就像下面這樣:
    sudo npm install -g coffee-script node-gyp
    npm install

  具體內容可以看下面這兩個頁面的介紹:

https://docs.npmjs.com/misc/scripts#user

https://docs.npmjs.com/getting-started/fixing-npm-permissions

  大致意思就是說:如果npm是在root賬戶下執行的話,它會將uid改成當前賬戶,或者uid的值從user配置檔案中獲取,而預設情況下uid的值為nobody。所以在root賬戶下執行npm install時需要將unsafe-perm選項加上。

相關文章