Reading files
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.
Checking for file existence
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...