使用 Node.js 读取文件

贡献者

The simplest way to read a file in Node.js is to use the fs.readFile() method, passing it the file path, encoding and a callback function that will be called with the file data (and the error):

JS

Alternatively, you can use the synchronous version fs.readFileSync():

JS

You can also use the promise-based fsPromises.readFile() method offered by the fs/promises module:

JS

All three of fs.readFile(), fs.readFileSync() and fsPromises.readFile() read the full content of the file in memory before returning the data.

This means that big files are going to have a major impact on your memory consumption and speed of execution of the program.

In this case, a better option is to read the file content using streams.