Writing a file to the home directory when running `npm install`

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

For this, I did in package.json :

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

And in /installation/preinstall.js (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 is the error EACCESS even if I started it with sudo ?

Running Ubuntu 14.04, if that matters.

+3
source share
1 answer

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

So this problem is here. HOME or USERPROFILE environment variables remain unchanged, but the user is nobody .

However --unsafe-perm prevents this:

 sudo npm install foo -g --unsafe-perm 
+2
source

Source: https://habr.com/ru/post/969617/


All Articles