sudo npm install -g leaves ~/.npm/anonymous-cli-metrics.json with root.root ownership

Background: the official instructions recommend to run npm as root using sudo when updating npm to the latest version. This is necessary, for instance, when node was installed using the official instructions on a Linux OS.

In the course of doing so, npm creates a file:

$ ls -l .npm/anonymous-cli-metrics.json 
-rw-r--r-- 1 root root 171 May 26 18:57 .npm/anonymous-cli-metrics.json

Subsequently, this file can be read, but not written when npm is used in the usual fashion (that is, to install packages non-globally).

The relevant code in lib/utils/metrics.js ignores when writes to this file fail, as would be the case when issuing subsequent commands as the regular user. For instance,

$ strace -ff npm install react |& grep anonymous
[pid  5394] openat(AT_FDCWD, "/home/gback/.npm/anonymous-cli-metrics.json", O_RDONLY|O_CLOEXEC) = 20
[pid  5394] openat(AT_FDCWD, "/home/gback/.npm/anonymous-cli-metrics.json", O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0666) = -1 EACCES (Permission denied)

My suggestion would be provide the proper ownership and permissions to this file, and under no circumstances to leave root.root owned files in my home directory just because I run npm as sudo and not sudo -H.

On a roll with the sudo bugs! Thanks.

There is a required template for #bugs, but easy to miss if you change category after you started writing topic. Would you mind reformatting to follow the template? (Nice bug and description otherwise, so I don’t want it to risk this getting downgraded or moved due to format.)