Search code examples
javascriptnode.jsexpressnode-csv-parse

How to use csv-parser to loop over rows in nodejs?


I am trying to write a script that will help me spit out boring code for work.

So at times, I get a .csv file that instructs me to create table fields, sometimes up to 50 at once! (Using AL, a Business Central programming language.)

I tried writing this;

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', () => {

    })

and had this test .csv file;

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

The idea is to read the .csv file, loop through every row, and write to a text file which then I would just past in my code file I am working on. Sounds boring maybe but could save me tons of time. I am a noob Javascript/Node developer so pardon my shortcomings.

After running the code, the output in text.txt is;

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";} 

Which is incorrect. The correct result should be;

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";} 

Guidance is highly appreciated. Thank you in advance!


Solution

  • This line:

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

    Should be:

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