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 ...

Get Getting Started with PhantomJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.