【问题标题】:CSV parser documentationCSV 解析器文档
【发布时间】:2019-04-27 15:43:13
【问题描述】:

我使用 fast-csv 作为我的转换器库已经有一段时间了。当客户端实际尝试上传实际包含“;”的 csv 文件时出现问题作为分隔符而不是默认的“,”。 NPM 文档明确表示所有方法都应该接受一个“选项”(不明白为什么不是对象)来实际切换这些标志。当然,我总是可以进入源 js 文件并手动更改分隔符,但我真的很想了解这个文档,因为它是我作为开发人员成长的一部分,但我仍然无法掌握它如何在我的代码上解析它时实际使用这些选项(分隔符)。如果你们也没有人能理解它,也许您对 javascript 上的 csv 解析器有一些建议?也许手动脚本会更加通用和有用?

来自(npm 上的 fast-csv)的文档示例:

All methods accept the following options

    objectMode=true: Ensure that data events have an object emitted rather than the stringified version set to false to have a stringified buffer.
    headers=false: Set to true if you expect the first line of your CSV to contain headers, alternatly you can specify an array of headers to use. You can also specify a sparse array to omit some of the columns.
    ignoreEmpty=false: If you wish to ignore empty rows.
    discardUnmappedColumns=false: If you want to discard columns that do not map to a header.
    strictColumnHandling=false: If you want to consider empty lines/lines with too few fields as errors - Only to be used with headers=true
    renameHeaders=false: If you want the first line of the file to be removed and replaced by the one provided in the headers option - Only to be used with headers=[String]
    delimiter=',': If your data uses an alternate delimiter such as ; or \t. 

另外,这里有一个示例代码,说明它是如何工作的,以及我如何使用它(使用管道):

var stream = fs.createReadStream("my.csv");

var csvStream = csv()
    .on("data", function(data){
         console.log(data);
    })
    .on("end", function(){
         console.log("done");
    });

stream.pipe(csvStream);

//or

var csvStream = csv
    .parse()
    .on("data", function(data){
         console.log(data);
    })
    .on("end", function(){
         console.log("done");
    });

stream.pipe(csvStream);

PS:我试过在其他地方(包发布的地方)询问它,但没有回复。

【问题讨论】:

    标签: javascript node.js csv npm fs


    【解决方案1】:

    NPM 文档明确指出所有方法都应该接受 一个“选项”(不明白为什么不是一个对象)来实际切换 这些标志

    引用的文本基本上意味着所有方法都接受所谓的options 对象作为它们的最后一个参数。您可以通过在该对象中设置相应的字段来指定备用分隔符。

    但我真的很想了解这个文档,因为它的全部 我作为开发人员成长的一部分

    如果您觉得文档中没有明确解释某些内容,我强烈建议您查看tests。对于您所描述的确切场景,实际上有一个测试用例:

    it.should("support semicolon delimiters", function (next) {
        var actual = [];
        csv
            .fromPath(path.resolve(__dirname, "./assets/test16.txt"), {headers: true, delimiter: ";"})
            .on("data", function (data) {
                actual.push(data);
            })
            .on("error", next)
            .on("end", function (count) {
                assert.deepEqual(actual, expected14);
                assert.equal(count, actual.length);
                next();
            });
    });
    

    【讨论】:

    • 非常感谢您的宝贵时间和建议,像您这样的人让这个地方变得很棒!
    猜你喜欢
    • 2017-06-24
    • 2015-12-10
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多