maxlath
maxlath

Reputation: 1841

where should a module write files?

I wrote a CLI module, wikidata-cli, that for a certain command (wd props) caches results as files in the module directory: node_modules/wikidata-cli/props/some-file. It works in my local setup where node and npm were installed in my home folder (using nvm), but other people having installed node/npm from their package manager, probably with sudo rights, encounter issues: once installed, the module loses the permission to modify the module directory and they get errors of the kind EACCES: permission denied, open '/usr/lib/node_modules/wikidata-cli/props/de.json'

I tried changing the access permission during the postinstall script - "postinstall": "mkdir -p props && chown -R 666 props" - but had to revert it was blocking any installation with a operation forbidden error.

Any clue were this kind of file is expected to be written in a cross-platform compatible way?

Upvotes: 3

Views: 83

Answers (1)

Jonathan Gilbert
Jonathan Gilbert

Reputation: 3840

If you're looking for the code to be able to write files no matter which user runs it, then there's really only one answer: The only folder that the current user a) is guaranteed to be able to write to, and b) won't encounter conflicts between different users accessing the same paths, is the user's own home directory.

You could use something like this to derive a path that the current user can definitely access:

var homePath = process.env.HOME || process.env.USERPROFILE; // POSIX || Win32

var moduleDataPath = path.join(homePath, ".wikidata-cli");

if (!fs.existsSync(moduleDataPath))
    fs.mkdirSync(moduleDataPath);

Upvotes: 1

Related Questions