JS文件上传:检测编码

DCH*_*DCH 5 javascript csv character-encoding node.js

因此,我尝试在前端使用 AngularJS,在后端使用 NodeJS 编写一个 CSV 文件导入器。我的问题是,我不确定传入 CSV 文件的编码。有没有办法自动检测呢?

我首先尝试使用 FileReader.readAsDataURL() 并在 Node 中进行检测。但文件内容将是 Base64 编码的,所以我不能这样做(当我解码文件时,我已经需要知道编码)。如果我执行 FileReader.readAsText(),我还需要事先知道编码。我也无法在初始化 FileReader 之前执行此操作,因为实际的文件对象似乎不包含文件内容。

我当前的代码:

generateFile = function(file){
    reader = new FileReader();
    reader.onload = function (evt) {
        if (checkSize(file.size) && isTypeValid(file.type)) {
            scope.$apply(function () {
                scope.file = evt.target.result;
                file.encoding = Encoding.detect(scope.file);
                if (angular.isString(scope.fileName)) {
                    return scope.fileName = name;
                }
            });
            if (form) {
                form.$setDirty();
            }
            scope.fileArray.push({
                name: file.name,
                type: file.type,
                size: file.size,
                date: file.lastModified,
                encoding: file.encoding,
                file: scope.file
            });
            --scope.pending;
            if (scope.pending === 0){
                scope.$emit('file-dropzone-drop-event', scope.fileArray);
                scope.fileArray = [];
            }
        }
    };
    let fileExtExpression = /\.csv+$/i;
    if(fileExtExpression.test(file.name)){
        reader.readAsText(file);
    }
    else{
        reader.readAsDataURL(file);
    }
    ++scope.pending;
}
Run Code Online (Sandbox Code Playgroud)

这是不可能做到的还是我做错了什么?我什至尝试使用 FileReader.readAsArrayBuffer() 解决此问题并从那里提取文件头,但这对我来说太复杂和/或似乎不起作用。

gui*_*lim 4

readAsBinaryString()我建议您使用FileReader打开 CSV 。这就是窍门。然后您可以使用库jschardet检测编码

更多信息请参见:CSV 编码检测 in javascript