【问题标题】:How to check if fs.read() is empty如何检查 fs.read() 是否为空
【发布时间】:2018-09-14 01:45:01
【问题描述】:

我需要先检查文件是否为空,然后才能放入JSON.parse()

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

我知道该文件存在于fs.exists(),但是如何在将其放入JSON.parse() 之前检查该文件是否不包含任何字符串?

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

返回:

SyntaxError: JSON Parse error: Unexpected EOF

【问题讨论】:

    标签: javascript phantomjs filesystems fs


    【解决方案1】:

    试试这个:

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

    【讨论】:

      【解决方案2】:

      我也在寻找一种解决方案来确定文件是否为空。找到下面的代码,效果很好。

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

      您可以检查 stat.size 是否为 0 并执行您的逻辑。

      【讨论】:

        猜你喜欢
        • 2017-11-15
        • 2020-05-29
        • 2018-04-02
        • 2016-04-05
        • 2018-01-08
        • 2020-09-25
        • 2012-01-15
        • 2016-07-16
        • 2021-08-14
        相关资源
        最近更新 更多