Reading from a file
In our discussion of file descriptors we touched on one method of opening a file, fetching a file descriptor, and ultimately pushing or pulling data through that reference. Reading files is a common operation. Sometimes managing a read buffer precisely may be necessary, and Node allows byte-by-byte control. In other cases one simply wants a no-frills stream that is simple to use.
Reading byte by byte
The fs.read
method is the most low-level way Node offers for reading files.
fs.read(fd, buffer, offset, length, position, callback)
Files are composed of ordered bytes, and these bytes are addressable by their position
, relative to the beginning of in the file (position zero [0]). Once we have a file descriptor fd
, we can begin to read length
number of bytes and insert those into a Buffer
object buffer
, insertion beginning at a given buffer offset
. For example, to copy the 8366 bytes beginning at position
309 of readable file fd
into a buffer
beginning at an offset
of 100, we...