简体   繁体   中英

read csv headers of local file in angularjs

I'm currently reading csv headers using following js code -

var r = new FileReader();
r.onload = function(e) {
    var contents = e.target.result;
    contents = contents.split(/\r\n|\n/);
    var i = 0,
        flag = false,
        headers;
    while (i < contents.length && flag == false) {
        if (contents[i] != '') {
            headers = contents[i]
            flag = true;
        }
        i++;
    }
    vm.fileHeaders = headers.split(",").map(function(item) { return item.trim() && item.replace(/['"]+/g, ''); });
    return true;
};
r.readAsText(item);

This code reads the whole file first & then returns headers. But it takes more time for large sized files. I want to modify this code that will only read the header & not the whole data, So that it'll take less time for large files too.

Found PapaParse as a quick solution!

Papa.parse(item, {
    worker: true,
    skipEmptyLines: true,
    step: function(results, parser) {
        parser.abort();
        vm.fileHeaders = results.data[0] || undefined;
        results = null;
        return vm.fileHeaders;
    },
    complete: function(results){
        results = null;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM