Synchronous File Reading

The synchronous method of file reading involves reading the data from a file before returning execution to the running thread. This provides the advantage of allowing you to read multiple times in the same section of code, but it can be a disadvantage if the file reads hold up other threads, as discussed earlier.

To read to a file synchronously, first open it by using openSync() to get a file descriptor and then use readSync() to read data from the file. The following is the syntax for readSync():

fs.readSync(fd, buffer, offset, length, position)

The fd parameter is the file descriptor that openSync() returns. The buffer parameter specifies the Buffer object that data will be read into from the file. The offset parameter specifies the index in the buffer to begin writing data; if you want to begin at the current index in the buffer, this value should be null. The length parameter specifies the number of bytes to read; to write until the end of the buffer, specify null. The position argument specifies the position in the file to begin reading. To use the current file position, specify null for this value.

The code in Listing 6.6 shows how to implement basic synchronous reading to read a chunk of string data from a file. Figure 6.6 shows the output of the code in Listing 6.6.

Listing 6.6 file_read_sync.js: Performing synchronous reads from a file


01 var fs = require('fs'),
02 fd = fs.openSync('../data/ veggie.txt', 'r'),
03 var veggies = "";
04 do {
05   var buf = new Buffer(5);
06   buf.fill();
07   var bytes = fs.readSync(fd, buf, null, 5);
08   console.log("read %dbytes", bytes);
09   veggies += buf.toString();
10 } while (bytes > 0);
11 fs.closeSync(fd);
12 console.log("Veggies: " + veggies);


Image

Figure 6.6 Output of file_read_sync.js, reading synchronously from a file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.111.134