Write file in home directory when running `npm ins

2019-07-04 12:14发布

问题:

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

For this I did in package.json:

{
  ...
  "scripts": {
     "preinstall": "./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
));

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

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

Running Ubuntu 14.04, if it's relevant.

回答1:

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.

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

However, --unsafe-perm prevents this:

sudo npm install foo -g --unsafe-perm