如何检查 fs.read() 是否为空
How to check if fs.read() is empty
我需要先检查文件是否为空,然后才能将其放入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'));
Returns:
SyntaxError: JSON Parse error: Unexpected EOF
试试这个:
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'));
}
}
我也在寻找一个解决方案来确定文件是否为空。找到下面的代码,效果很好。
const stat = fs.statSync('./path/to/file');
console.log(stat.size);
您可以检查 stat.size 是否为 0 并执行您的逻辑。
我需要先检查文件是否为空,然后才能将其放入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'));
Returns:
SyntaxError: JSON Parse error: Unexpected EOF
试试这个:
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'));
}
}
我也在寻找一个解决方案来确定文件是否为空。找到下面的代码,效果很好。
const stat = fs.statSync('./path/to/file');
console.log(stat.size);
您可以检查 stat.size 是否为 0 并执行您的逻辑。