process.initgroups(user, extraGroup)
process.initgroups() 方法读取 /etc/group 文件并初始化组访问列表,使用用户所属的所有组。这是一个需要特权的操作,要求 Node.js 进程拥有 root 权限或 CAP_SETGID 能力。
【The process.initgroups() method reads the /etc/group file and initializes
the group access list, using all groups of which the user is a member. This is
a privileged operation that requires that the Node.js process either have root
access or the CAP_SETGID capability.】
删除权限时要小心:
【Use care when dropping privileges:】
import { getgroups, initgroups, setgid } from 'node:process';
console.log(getgroups()); // [ 0 ]
initgroups('nodeuser', 1000); // switch user
console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]
setgid(1000); // drop root gid
console.log(getgroups()); // [ 27, 30, 46, 1000 ]const { getgroups, initgroups, setgid } = require('node:process');
console.log(getgroups()); // [ 0 ]
initgroups('nodeuser', 1000); // switch user
console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]
setgid(1000); // drop root gid
console.log(getgroups()); // [ 27, 30, 46, 1000 ]此功能仅在 POSIX 平台上可用(即不支持 Windows 或 Android)。
此功能在 Worker 线程中不可用。
【This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in Worker threads.】