There are various reasons as to why we need to read a file within our script; for most examples, we may need to read a configuration file that is relatively needed in our script execution. Let us learn how to read files using the API.
Before we actually read the file content, it is better to check the file's existence so that we can prevent possible file reading errors. Using the API, we can check if the file exists using the exists
function.
fs.exists('/data/myfiles/config.txt')
However, this function does not guarantee that the file we are checking is a true file; it may be a directory. The path that can be passed onto the function might be a folder path, which also returns true
if the folder path is correct and if it does exist. So, to make it more accurate, we can also combine the testing of the file's existence using the isFile
function. This function also accepts the file path as a parameter and returns true
if the path is a file (and not a directory).
var filePath = '/book/chapter7/sources/file1.js'; if( fs.exists(filePath) && fs.isFile(filePath) ) {
With this function, rest assured that the file exists when we opened the file for reading.
Now, we can open the file for reading using the open(path, mode)
function. The mode
parameter can be any one of the following values:
File open mode |
Functions |
---|---|
|
Open file for reading |
|
File mode is set for writing |
|
Append mode |
|
Reading binary files |
|
Writing binary files |
We will now use the open
function to read a text file; see the following code:
var ins = fs.open(filePath, 'r'),
If the file is opened successfully, it will return an object of the stream
type. This object has the capability to manipulate the content of the opened file either for reading or writing.
var ins = fs.open(filePath, 'r'), console.log(ins.read());
In the preceding lines of code, we use the object stream and issue the read()
function. This will read all the content of the file and return it to the method. We can stream that data as we like, or simply print it to the console.
Let us modify the preceding little code and make it more functional. For example, our script will need to read a file that contains some configuration details, and this file is in JSON format, as follows:
{ "home": "/phantomjs/src", "debug": false }
As we now know, we can actually read its entire contents just by using the read()
function, and with that, it will return the content of the file. Using JavaScript JSON parsing, we can convert the text into a functional JSON object.
var ins = fs.open(filePath, 'r'), var data = ins.read(); var config = JSON.parse(data); console.log("Home: " + config.home);
Alternatively, in the preceding lines of code, we can combine the first three lines into one line as follows:
var config = JSON.parse(fs.open(filePath, 'r').read());
If we run our code, it should display that the home directory is /phantomjs/src
, which comes from the file that was read:
Alternatively, we can also read the file line by line. In some cases, this will be necessary, especially when we are processing each line separately when parsing a CSV file. We can do this by using the readLine()
function instead. On every function call, the readLine()
function will return one line of string from the file. We can parse each line by using the split()
function to tokenize the string.
var ins = fs.open(filePath, 'r'), while(!ins.atEnd()) { var buffer = ins.readLine(); site = buffer.split(/s*,s*/); console.log(site[0]); console.log('---------------------------'), console.log('Web: ' + site[1]); console.log('Since: ' + site[2] + ' '), }
If we are reading the file line by line, then we need to check whether we have reached the end of the file. We can do this by using the atEnd()
function of the stream
object. This function will return true
if we reach the end of the file; otherwise, it will return false
.
If we have the following CSV content:
Facebook,www.facebook.com,2004 Foursquare,www.foursquare.com,2009 Google+,plus.google.com,2011
And we execute our script against that CSV content, then we will have the following output:
18.117.91.2