Search code examples
javascriptphantomjsfilesystemsfs

How to check if fs.read() is empty


I need to check whether a file is empty before I can put it in JSON.parse().

if (fs.exists('path/to/file')) { // true
   return JSON.parse(fs.read('path/to/file'));
}

I know that the file exists by fs.exists(), but how can I check if the file contains no strings before I can put it in JSON.parse()?

JSON.parse(fs.read('path/to/file'));

Returns:

SyntaxError: JSON Parse error: Unexpected EOF


Solution

  • Try this:

    if (fs.exists('path/to/file')) {
        if (fs.read('path/to/file').length === 0) {
            //Code to be executed if the file is empty
        } else {
            return JSON.parse(fs.read('path/to/file'));
        }
    }