Robbert
Robbert

Reputation: 1330

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

Upvotes: 2

Views: 6739

Answers (3)

Xitcod13
Xitcod13

Reputation: 6079

Here is a solution that is not deprecated. just checking for statSync will crash if file doesn't exist.

if(!fs.existsSync('./path/to/file') || fs.statSync('./path/to/file').size == 0) {
  // file doesn't exist or is empty.
} else {
  // process a non empty file
}

Upvotes: 2

Balasubramanian S
Balasubramanian S

Reputation: 1433

I was also looking for a solution to find out if the file is empty or not. Found the below code and it works great.

const stat = fs.statSync('./path/to/file');
console.log(stat.size);

You can check if the stat.size is 0 and do your logic.

Upvotes: 6

D. Pardal
D. Pardal

Reputation: 6597

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'));
    }
}

Upvotes: 4

Related Questions