Reading and Writing Files Asynchronously
Earlier in this chapter, we wrote a series of Node.js programs that could watch files for changes. Now letâs explore Node.jsâs methods for reading and writing files. Along the way weâll see two common error-handling patterns in Node.js: error events on EventEmitters and err callback arguments.
There are a few approaches to reading and writing files in Node. The simplest is to read in or write out the entire file at once. This technique works well for small files. Other approaches read and write by creating Streams or staging content in a Buffer. Hereâs an example of the whole-file-at-once approach:
â | â'use strict'â; |
â | âconstâ fs = require(â'fs'â); |
â |
Get Node.js 8 the Right Way now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.