嗨,我有一种情况,我想在读取文件时区分plain text file
和json file
现在我无法区分plain text content
和json content
这是我在做什么:
var fs = require('fs');
var path = require('path');
function checkforJson(string){
return typeof string === 'object';
}
var fileLocation = path.join(__dirname, 'watchfolder/');
fs.readFile(fileLocation, (eventType, filename) => {
var filecontent = fs.readFileSync(fileLocation+""+filename);
filecontent = filecontent.toString();
if(checkforJson(filecontent)){
// json file
}else{
// plain text file
}
});
最受欢迎:解决此问题的最佳方法
问题:,但是出于某些最佳原因,上述检查由于某些原因而无法正常工作?
答案 0 :(得分:1)
它们之间没有区别,因为JSON是字符串,而JSON文件是文本文件。
在这种情况下,考虑到JSON文件与其余文本文件之间的区别在于它具有.json扩展名,因此可能是:
if (/\.json$/i.test(filename)) {
const data = JSON.parse(filecontent);
} else {
// plain text file
}
如果文件应按内容区分,则应在文件上尝试JSON.parse
:
try {
const data = JSON.parse(filecontent);
} catch (err) {
// plain text file
}
在第二种情况下,无法判断这不是JSON还是存在格式问题的JSON。
答案 1 :(得分:0)
为什么不将try-catch
块与JSON.parse
一起使用?
function checkforJson(json) {
try {
return JSON.parse(json);
}
catch (e){
return null;
}
}
答案 2 :(得分:0)
我认为您可以像这样添加一个正则表达式:
var JSONorTXT = function(fileToCheck)
let isJSON = regex.test(/.*$\.json/)
if (isJSON === true) {
var filetype = "json"
return filetype
}
else {
var filetype = "txt"
return filetype
}
我不确定,但这应该可以。