性能考量


fs.readFile() 方法每次一块地异步读取文件内容到内存中,允许事件循环在每个块之间转换。 这允许读取操作对可能使用底层 libuv 线程池的其他活动的影响较小,但意味着将完整文件读入内存需要更长的时间。

额外的读取开销在不同的系统上可能会有很大差异,并且取决于正在读取的文件类型。 如果文件类型不是常规文件(例如管道)并且 Node.js 无法确定实际文件大小,则每次读取操作将加载 64 KiB 的数据。 对于常规文件,每次读取将处理 512 KiB 的数据。

对于需要尽可能快地读取文件内容的应用程序,最好直接使用 fs.read() 并让应用程序代码管理读取文件本身的全部内容。

Node.js GitHub 问题 #25741 提供了有关不同 Node.js 版本中多个文件大小的 fs.readFile() 性能的详细信息和详细分析。

The fs.readFile() method asynchronously reads the contents of a file into memory one chunk at a time, allowing the event loop to turn between each chunk. This allows the read operation to have less impact on other activity that may be using the underlying libuv thread pool but means that it will take longer to read a complete file into memory.

The additional read overhead can vary broadly on different systems and depends on the type of file being read. If the file type is not a regular file (a pipe for instance) and Node.js is unable to determine an actual file size, each read operation will load on 64 KiB of data. For regular files, each read will process 512 KiB of data.

For applications that require as-fast-as-possible reading of file contents, it is better to use fs.read() directly and for application code to manage reading the full contents of the file itself.

The Node.js GitHub issue #25741 provides more information and a detailed analysis on the performance of fs.readFile() for multiple file sizes in different Node.js versions.