【问题标题】:How to use csv-parser to loop over rows in nodejs?如何使用 csv-parser 遍历 nodejs 中的行?
【发布时间】:2020-07-30 08:44:17
【问题描述】:

我正在尝试编写一个脚本来帮助我吐出无聊的工作代码。

所以有时,我会得到一个 .csv 文件,指示我创建表格字段,有时一次最多可创建 50 个! (使用 AL,一种业务中心编程语言。)

我试着写这个;

const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');
const CreatesFile = fs.createWriteStream(path.resolve(__dirname, 'final.txt'), {
    flags: 'a' //flags: 'a' preserved old data
})

    fs.createReadStream(path.resolve(__dirname, 'AutomateVAR.csv'))
    .on('error', () => {
        // handle error
    })
    .pipe(csv())
    .on('data', (row) => {
        if (row["Var Type"] == "Text" || "Code") {
            CreatesFile.write( `field(; "${row["Var Name"]}"; ${row["Var Type"]}[${row["Var Length"]}]) {DataClassification = CustomerContent;} ` + '\r\n'); 
        }
         if (row["Var Type"] == "Boolean") {
            CreatesFile.write( `field(; "${row["Var Name"]}"; ${row["Var Type"]}) {DataClassification = CustomerContent;} ` + '\r\n');
        }
         if (row["Var Type"] == "Option")
        {
            CreatesFile.write( `field(; "${row["Var Name"]}"; ${row["Var Type"]}) { OptionMembers = ${row["Var Value"]};} ` + '\r\n');
        }
    })
    .on('end', () => {

    })

并拥有此测试 .csv 文件;

Var Name,Var Type,Var Value,Var Length
Customer,Code,,20
Employee,Text,,50
Cash Customer,Boolean,,
Car Type,Option,"""One"",""Two""",

这个想法是读取 .csv 文件,循环遍历每一行,然后写入一个文本文件,然后我将在我正在处理的代码文件中传递该文件。听起来可能很无聊,但可以为我节省大量时间。我是一个菜鸟 Javascript/Node 开发人员,所以请原谅我的缺点。

运行代码后,text.txt中的输出为:

field(; "Customer"; Code[20]) {DataClassification = CustomerContent;} 
field(; "Employee"; Text[50]) {DataClassification = CustomerContent;} 
field(; "Cash Customer"; Boolean[]) {DataClassification = CustomerContent;} 
field(; "Cash Customer"; Boolean) {DataClassification = CustomerContent;} 
field(; "Car Type"; Option[]) {DataClassification = CustomerContent;} 
field(; "Car Type"; Option) { OptionMembers = "One","Two";} 

这是不正确的。正确的结果应该是;

field(; "Customer"; Code[20]) {DataClassification = CustomerContent;} 
field(; "Employee"; Text[50]) {DataClassification = CustomerContent;} 
field(; "Cash Customer"; Boolean) {DataClassification = CustomerContent;} 
field(; "Car Type"; Option) { OptionMembers = "One","Two";} 

非常感谢您的指导。提前感谢您!

【问题讨论】:

    标签: javascript node.js express node-csv-parse


    【解决方案1】:

    这一行:

    if (row["Var Type"] == "Text" || "Code") {
    

    应该是:

    if (row["Var Type"] == "Text" || row["Var Type"] == "Code") {
    

    【讨论】:

    • 这又快又好!万分感谢!介意告诉我什么是“文本”|| “代码”评估为?
    • || 的右侧将始终评估为真。例如。 if ("Code") 永远是真的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    相关资源
    最近更新 更多