运行`npm install`时将文件写入主目录 [英] Write file in home directory when running `npm install`

查看:156
本文介绍了运行`npm install`时将文件写入主目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在安装foo模块时,作为开发人员,我想编写~/.foo.json文件(其中~/是用户的主目录).

When install a foo module, as developer, I want to write ~/.foo.json file (where ~/ is the user's home directory).

为此,我在package.json中做了:

{
  ...
  "scripts": {
     "preinstall": "./installation/preinstall.js"
  },
  ...
}

/installation/preinstall.js(可执行文件)中,我有:

And in /installation/preinstall.js (that is executable), I have:

#!/usr/bin/env node

// Dependencies
var Fs = require("fs");

function getUserHome() {
    return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}

console.log("Creating configuration file ...")
Fs.writeFileSync(getUserHome() + "/" + ".foo.json", JSON.stringify(
    require("./sample-config"), null, 4
));

运行sudo npm install ...@... -g时,我得到以下输出:

When running sudo npm install ...@... -g I get the following output:

ionicabizau@laptop:~$ sudo npm install ...@...-alpha1 -g                           
npm http GET https://registry.npmjs.org/...
npm http 304 https://registry.npmjs.org/...

> ...@...-alpha1 preinstall /usr/lib/node_modules/...
> ./installation/preinstall.js

Creating configuration file ...

fs.js:432
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: EACCES, permission denied '/home/ionicabizau/.foo.json'
    at Object.fs.openSync (fs.js:432:18)
    at Object.fs.writeFileSync (fs.js:971:15)
    at Object.<anonymous> (/usr/lib/node_modules/.../installation/preinstall.js:11:4)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

为什么EACCESS错误,即使我用sudo运行它?

Why EACCESS error, even if I run it with sudo?

运行Ubuntu 14.04(如果相关).

Running Ubuntu 14.04, if it's relevant.

推荐答案

根据

According to documentation, If npm was invoked with root privileges, then it will change the uid to the user account or uid specified by the user config, which defaults to nobody. Set the unsafe-perm flag to run scripts with root privileges.

所以,这就是这里的问题.环境变量HOMEUSERPROFILE保持不变,但用户为nobody.

So, that's the problem here. The environment variables HOME or USERPROFILE remain the same, but the user is nobody.

但是,--unsafe-perm可以防止这种情况:

However, --unsafe-perm prevents this:

sudo npm install foo -g --unsafe-perm

这篇关于运行`npm install`时将文件写入主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆