process.initgroups(user, extraGroup)
process.initgroups()
方法读取 /etc/group
文件并使用用户所属的所有组初始化组访问列表。
这是一个特权操作,要求 Node.js 进程具有 root
访问权限或 CAP_SETGID
能力。
删除权限时要小心:
import { getgroups, initgroups, setgid } from 'node:process';
console.log(getgroups()); // [ 0 ]
initgroups('nodeuser', 1000); // 切换用户
console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]
setgid(1000); // 删除 root 的 gid
console.log(getgroups()); // [ 27, 30, 46, 1000 ]
const { getgroups, initgroups, setgid } = require('node:process');
console.log(getgroups()); // [ 0 ]
initgroups('nodeuser', 1000); // 切换用户
console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]
setgid(1000); // 删除 root 的 gid
console.log(getgroups()); // [ 27, 30, 46, 1000 ]
此功能仅适用于 POSIX 平台(即不适用于 Windows 或安卓)。
此特性在 Worker
线程中不可用。
user
<string> | <number> The user name or numeric identifier.extraGroup
<string> | <number> A group name or numeric identifier.
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 ]
This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in Worker
threads.