在 Node.js 中读取和写入文件 - 完整的现代指南
File operations are at the heart of most Node.js applications. Whether you’re building a web server that serves static assets, processing CSV files, handling user uploads, or working with configuration files, knowing how to efficiently read and write files is absolutely essential.
文件操作是大多数 Node.js 应用程序的核心。无论您是在构建一个提供静态资源的 web 服务器,处理 CSV 文件,处理用户上传,还是处理配置文件,了解如何高效地读取和写入文件是绝对必要的。
There are several ways to handle file operations in Node.js (callback-based APIs, synchronous methods, and promise-based approaches). While callback and sync methods are still valid and occasionally useful, they’re being used less and less these days. The Node.js ecosystem has shifted toward more ergonomic patterns, moving away from callback hell and blocking operations in favor of cleaner async/await syntax and non-blocking promise-based APIs.
在 Node.js 中处理文件操作有几种方法(基于回调的 API、同步方法和基于 Promise 的方法)。虽然回调和同步方法仍然有效且偶尔有用,但这些天它们的使用越来越少。Node.js 生态系统已经转向更符合人体工程学的模式,远离回调地狱和阻塞操作,转而采用更清晰的 async/await 语法和非阻塞的基于 Promise 的 API。
In this comprehensive guide, we’ll focus on the modern approaches to file handling in Node.js. We’ll start with the simplest methods using promises, then dive into more advanced techniques like using file handles and streaming: a clever approach that can handle massive files without breaking your application.
在本综合指南中,我们将重点关注 Node.js 中现代的文件处理方法。我们将从使用 Promise 的最简单方法开始,然后深入探讨更高级的技术,如使用文件句柄和流:一种巧妙的方法,可以处理大型文件而不会破坏您的应用程序。
Let’s dive in and master file operations in Node.js!
让我们深入学习并掌握 Node.js 中的文件操作!
Code examples
代码示例
All the code examples in this article can be found on GitHub.
本文中的所有代码示例都可以在 GitHub 上找到。
Reading and Writing Files with Node.js Promises (fs/promises)
使用 Node.js Promises (fs/promises) 读取和写入文件
The most straightforward way to work with files in modern Node.js is using the node:fs/promises module with functions like readFile() and writeFile(). This gives us a clean, promise-based API that works beautifully with async/await.
在现代 Node.js 中处理文件的最简单方法是使用 node:fs/promises 模块,结合 readFile() 和 writeFile() 等函数。这为我们提供了一个干净的、基于 Promise 的...