模块应该在哪里写入文件?

where should a module write files?

我写了一个 CLI 模块,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:一旦安装,该模块就失去了修改模块目录的权限,并且会出现 EACCES: permission denied, open '/usr/lib/node_modules/wikidata-cli/props/de.json'

之类的错误

我尝试在安装后脚本期间更改访问权限 - "postinstall": "mkdir -p props && chown -R 666 props" - 但不得不 revert 它阻止了任何安装并出现 operation forbidden 错误。

有什么线索是希望以跨平台兼容的方式编写这种文件吗?

如果您正在寻找能够写入文件的代码,无论哪个用户运行它,那么实际上只有一个答案:当前用户 a) 保证能够写入的唯一文件夹,b)不会遇到不同用户访问相同路径的冲突,是用户自己的家目录。

您可以使用类似这样的方法来导出当前用户绝对可以访问的路径:

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

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

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