最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if fs.read() is empty - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Apr 4, 2018 at 13:12 RobbertRobbert 1,3306 gold badges30 silver badges67 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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.

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

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
}
发布评论

评论列表(0)

  1. 暂无评论