UV_THREADPOOL_SIZE=size


将 libuv 的线程池中使用的线程数设置为 size 个线程。

Node.js 尽可能使用异步的系统 API,但在它们不存在的情况下,libuv 的线程池用于基于同步的系统 API 创建异步的 node API。 使用线程池的 Node.js API 有:

  • 所有 fs API,除了文件监视器 API 和那些显式同步的
  • 异步加密 API,例如 crypto.pbkdf2()crypto.scrypt()crypto.randomBytes()crypto.randomFill()crypto.generateKeyPair()
  • dns.lookup()
  • 所有 zlib API,除了那些显式同步的

因为 libuv 的线程池有固定的大小,这意味着如果这些 API 中的任何一个由于某种原因需要很长时间,则在 libuv 的线程池中运行的其他(看似无关的)API 的性能将会下降。 为了缓解此问题,潜在的解决方案是通过将 'UV_THREADPOOL_SIZE' 环境变量设置为大于 4(其当前默认值)的值来增加 libuv 线程池的大小。 有关更多信息,请参阅 libuv 线程池文档

Set the number of threads used in libuv's threadpool to size threads.

Asynchronous system APIs are used by Node.js whenever possible, but where they do not exist, libuv's threadpool is used to create asynchronous node APIs based on synchronous system APIs. Node.js APIs that use the threadpool are:

  • all fs APIs, other than the file watcher APIs and those that are explicitly synchronous
  • asynchronous crypto APIs such as crypto.pbkdf2(), crypto.scrypt(), crypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()
  • dns.lookup()
  • all zlib APIs, other than those that are explicitly synchronous

Because libuv's threadpool has a fixed size, it means that if for whatever reason any of these APIs takes a long time, other (seemingly unrelated) APIs that run in libuv's threadpool will experience degraded performance. In order to mitigate this issue, one potential solution is to increase the size of libuv's threadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value greater than 4 (its current default value). For more information, see the libuv threadpool documentation.