当使用
一个谜!
npm
调用时,使用fs.readFileSync
的脚本会抛出EACCESS异常,但使用node
则不会。
在一台古老的(2016年)Docker镜像上,我需要运行一个涉及Bower的postinstall
NPM脚本 (bower install --allow-root
),但每次运行时都会出现EACCES: permission denied, open '/root/.config/configstore/bower-github.json'
的错误。我发现使用npx bower
也会导致相同的问题。将npx bower
在Docker之外运行则正常。
通常情况下,我可以轻松地处理这些问题,因为它们通常会在某人使用sudo
时出现误操作。解决这些问题的方法通常是将所有者更改回当前用户或只需使用sudo
和--allow-root
来运行bower命令 (示例1,示例2)。
然而,这不是这些问题之一。 我已经是root用户了!
完整的错误信息与类似问题的任何错误信息一样:
root@eaa32456c249:/var/www/myproj# npx bower --allow-root
/var/www/myproj/node_modules/bower/lib/node_modules/configstore/index.js:54
throw err;
^
Error: EACCES: permission denied, open '/root/.config/configstore/bower-github.json'
You don't have access to this file.
at Object.openSync (node:fs:585:3)
at Object.readFileSync (node:fs:453:35)
at Configstore.get (/var/www/myproj/node_modules/bower/lib/node_modules/configstore/index.js:35:38)
at new Configstore (/var/www/myproj/node_modules/bower/lib/node_modules/configstore/index.js:28:48)
at readCachedConfig (/var/www/myproj/node_modules/bower/lib/config.js:19:23)
at defaultConfig (/var/www/myproj/node_modules/bower/lib/config.js:11:12)
at Object.<anonymous> (/var/www/myproj/node_modules/bower/lib/index.js:16:32)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32) {
errno: -13,
syscall: 'open',
code: 'EACCES',
path: '/root/.config/configstore/bower-github.json'
我无法进一步提升我的权限,添加--allow-root
也没有任何作用。我甚至检查了相关模块,发现始终失败的调用只是这样的:
readFileSync(this.path, 'utf8');
当然,this.path
是 '/root/.config/configstore/bower-github.json'
。
我接着编写了这个小测试模块,它也能够正常运行:
root@eaa32456c249:/var/www/myproj# cat test.js
const execSync = require('child_process').execSync;
const fs = require('fs');
const path = '/root/.config/configstore/bower-github.json';
console.log('exec whoami: ', execSync('whoami').toString());
try {
const result = execSync('ls -l ' + path, { encoding: 'utf8' });
console.log('exec ls -l: ', result);
} catch (err) {}
try {
const parsed = JSON.parse(fs.readFileSync(path, 'utf8', { encoding: 'utf8' }));
console.log('parsed: ', parsed);
} catch (err) {
console.error(err.message);
}
root@eaa32456c249:/var/www/myproj# node test.js
exec whoami: root
exec ls -l: -rw-r--r-- 1 root root 3 Dec 8 22:55 /root/.config/configstore/bower-github.json
parsed: {}
一个谜!