在 npx 中使用权限模型


【Using the Permission Model with npx

如果你正在使用 npx 来执行 Node.js 脚本,你可以通过传递 --node-options 标志来启用权限模型。例如:

【If you're using npx to execute a Node.js script, you can enable the Permission Model by passing the --node-options flag. For example:】

npx --node-options="--permission" package-name 

这会为 npx 启动的所有 Node.js 进程设置 NODE_OPTIONS 环境变量,而不会影响 npx 进程本身。

【This sets the NODE_OPTIONS environment variable for all Node.js processes spawned by npx, without affecting the npx process itself.】

使用 npx 时的文件系统读取错误

上述命令可能会抛出 FileSystemRead 无效访问错误,因为 Node.js 需要文件系统的读取权限来定位和执行该包。为避免此情况:

【The above command will likely throw a FileSystemRead invalid access error because Node.js requires file system read access to locate and execute the package. To avoid this:】

  1. 使用全局安装的包 通过运行以下命令授予对全局 node_modules 目录的读取权限:

    npx --node-options="--permission --allow-fs-read=$(npm prefix -g)" package-name 
  2. 使用 npx 缓存 如果你只是临时安装该包或依赖 npx 缓存, 请授予 npm 缓存目录的读取权限:

    npx --node-options="--permission --allow-fs-read=$(npm config get cache)" package-name 

你通常传递给 node 的任何参数(例如 --allow-* 标志)也可以通过 --node-options 标志传递。这种灵活性使在使用 npx 时根据需要配置权限变得非常容易。

【Any arguments you would normally pass to node (e.g., --allow-* flags) can also be passed through the --node-options flag. This flexibility makes it easy to configure permissions as needed when using npx.】