Simple File Reading

The simplest method for reading data from a file is to use one of the readFile() methods. These methods read the full contents from a file into a data buffer. The following is the syntax for readFile() methods:

fs.readFile(path, [options], callback)
fs.readFileSync(path, [options])

The path parameter specifies the path to the file, which can be relative or absolute. The optional options parameter is an object that can contain encoding, mode, and flag properties that define the string encoding as well as the mode and flags used when opening the file. The asynchronous method also requires the callback parameter, which will be called when the file read has been completed.

The code in Listing 6.5 illustrates implementing a simple asynchronous readFile() request to read a JSON string from a configuration file and then use it to create a config object. Figure 6.5 shows the output of the code in Listing 6.5.

Listing 6.5 file_read.js code: Reading a JSON string file to an object


01 var fs = require('fs'),
02 var options = {encoding:'utf8', flag:'r'};
03 fs.readFile('config.txt', options, function(err, data){
04   if (err){
05     console.log("Failed to open Config File.");
06   } else {
07     console.log("Config Loaded.");
08     var config = JSON.parse(data);
09     console.log("Max Files: " + config.maxFiles);
10     console.log("Max Connections: " + config.maxConnections);
11     console.log("Root Path: " + config.rootPath);
12   }
13 });


Image

Figure 6.5 Output of file_read.js, reading a configuration file to an object.

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

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