Working with files
The ability to read and manipulate the is fundamental to server-side programming.
Node's fs
module provides this ability.
In this recipe, we'll learn how to read, write, and append to files in a synchronous manner. In the There's more... section, we'll explore how to perform the same operations asynchronously and incrementally.
Getting ready
We'll need a file to read.
We can use the following to populate a file with 1 MB of data:
$ node -p "Buffer.allocUnsafe(1e6).toString()" > file.dat
Note
Allocating buffers
When the Buffer
constructor is passed a number, the specified amount of bytes will be allocated from deallocated memory, data in RAM that was previously discarded. This means the buffer could contain anything. From Node 6 and above, passing a number to Buffer
is deprecated. Instead, we use Buffer.allocUnsafe
to achieve the same effect, or just Buffer.alloc
to have a zero-filled buffer (but at the cost of slower instantiation). To state the obvious, the file we generated...