我正在使用的网站允许用户上传必须遵守严格格式的数据集。当然,JSON文件(最重要的是必需的dataset_description.json文件)必须是Unicode。但是最近,我们让人们尝试上传以Latin-1编码的JSON数据集。这些上传失败,没有关于为什么的明确警告(编码错误)。我的目标是发出编码警告,以便这些用户知道为什么他们的上传失败。
为此,我需要检查JSON文件的编码类型...并且找不到任何执行此操作的Javascript方法。我尝试在Unix File
cmd之后建模,以输出编码类型,但是却努力将C音译为JS(而且,这是一个巨大的功能,我怀疑有更简单的方法)
有人对我如何读取JSON输入以检查Unicode和其他内容有任何想法吗?
此代码检查dataset_description.json是否存在:
const checkDatasetDescription = jsonContentsDict => {
let issues = []
console.log(jsonContentsDict)
const jsonFilePaths = Object.keys(jsonContentsDict)
console.log(jsonFilePaths)
const hasDatasetDescription = jsonFilePaths.some(path => {
return path == '/dataset_description.json'
})
if (!hasDatasetDescription) {
issues.push(new Issue({ code: 57 }))
} else {
const datasetDescription = jsonContentsDict['/dataset_description.json']
// check to ensure that the dataset description Authors are
// properly formatted - Author check is another function in the codebase
issues = issues.concat(checkAuthorField(datasetDescription.Authors))
}
return issues
}
此代码是读取文件内容的辅助方法。它需要一个文件对象和一个回调,并使用文件的二进制内容作为唯一参数来调用回调:
/* In the browser the file should be a file object.
* In node the file should be a path to a file.
*/
function readFile(file, annexed, dir) {
return new Promise((resolve, reject) => {
if (isNode) {
testFile(file, annexed, dir, function(issue, stats, remoteBuffer) {
if (issue) {
process.nextTick(function() {
return reject(issue)
})
}
if (!remoteBuffer) {
fs.readFile(file.path, 'utf8', function(err, data) {
console.log(arguments[2])
process.nextTick(function() {
return resolve(data)
})
})
}
if (remoteBuffer) {
process.nextTick(function() {
return resolve(remoteBuffer.toString('utf8'))
})
}
})
} else {
var reader = new FileReader()
reader.onloadend = function(e) {
if (e.target.readyState == FileReader.DONE) {
if (!e.target.result) {
return reject(new Issue({ code: 44, file: file }))
}
return resolve(e.target.result)
}
}
reader.readAsBinaryString(file)
}
})
}
因此,正在读取和评估文件,但是我不知道如何专门检查Unicode。