Now that we have a fairly good handle on network IO in NodeJS, it's time to focus our attention on file system IO. After this section, we'll see how files and network sockets are treated the same inside the event loop. Node takes care of the subtle differences for us, which means we can write consistent code.
First, we'll look at reading form files, followed by writing to files. We'll close the section with a look at streaming from one file to another, performing data transformations in between.
Let's start with a simple example that reads the entire contents of a file into memory. This will help us get a feel for doing asynchronous file IO:
// We need the "fs" module to read files. var fs = require('fs'); var path = require('path'); // The file path we're working with. var filePath = path.join(__dirname, 'words'); // Starts the timer for reading our "words" file. console.time('reading words'); // Reads the entire file into memory, then fires // a callback...