The synchronous method of file writing involves writing data to a file before returning execution to the running thread. This provides the advantage of allowing you to write multiple times in the same section of code, but it can be a disadvantage if the file writes hold up other threads, as discussed earlier.
To write to a file synchronously, first open it using openSync()
to get a file descriptor and then use fs.writeSync()
to write data to the file. The following is the syntax for fs.writeSync()
:
fs.writeSync(fd, data, offset, length, position)
The fd
parameter is the file descriptor that openSync()
returns. The data
parameter specifies the String
or Buffer
object that will be written to the file. The offset
parameter specifies the index in the data
parameter to begin reading from. If you want to begin at the current index in the string or buffer, this value should be null
. The length
parameter specifies the number of bytes to write; you can specify null
to write until the end of the data
buffer. The position
argument specifies the position in the file to begin writing; to use the current file position, specify null
for this value.
The code in Listing 6.2 shows how to implement basic synchronous writing to store a series of string data in a file. Figure 6.2 shows the output of the code in Listing 6.2.
1 var fs = require('fs'),
2 var veggieTray = ['carrots', 'celery', 'olives'];
3 fd = fs.openSync('../data/veggie.txt', 'w'),
4 while (veggieTray.length){
5 veggie = veggieTray.pop() + " ";
6 var bytes = fs.writeSync(fd, veggie, null, null);
7 console.log("Wrote %s %dbytes", veggie, bytes);
8 }
9 fs.closeSync(fd);