如何在Node.js中区分文本文件和JSON文件

时间:2018-10-14 14:35:33

标签: javascript node.js fs

嗨,我有一种情况,我想在读取文件时区分plain text filejson file

现在我无法区分plain text contentjson 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
    }
});

最受欢迎:解决此问题的最佳方法

问题:,但是出于某些最佳原因,上述检查由于某些原因而无法正常工作?

3 个答案:

答案 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
   }

我不确定,但这应该可以。