性能注意事项


【Performance Considerations】

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

【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.】

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

【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.】

对于需要尽可能快速读取文件内容的应用,最好直接使用 fs.read(),并让应用代码自行管理文件内容的完整读取。

【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.】

Node.js 的 GitHub 问题 #25741 提供了更多信息以及对不同 Node.js 版本中 fs.readFile() 在多种文件大小下性能的详细分析。

【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.】