Wednesday, 6 October 2021

csvtojson node.js (combine two codes)

How to combine these two codes, so it doesn't just covert csv to Json (first code), but also save this as an json array in an extra file?(second code) this (first) code converts csv file to json array:

const fs = require("fs");

let fileReadStream = fs.createReadStream("myCsvFile.csv");
let invalidLineCount = 0;

const csvtojson = require("csvtojson");
csvtojson({ "delimiter": ";", "fork": true })
.preFileLine((fileLineString, lineIdx)=> {
    let invalidLinePattern = /^['"].*[^"'];/;
    if (invalidLinePattern.test(fileLineString)) {
        console.log(`Line #${lineIdx + 1} is invalid, skipping:`, fileLineString);
        fileLineString = "";
        invalidLineCount++;
    }
    return fileLineString
})
.fromStream(fileReadStream) 
.subscribe((dataObj) => { 
    console.log(dataObj);
// I added the second code hier, but it wirtes the last object of the array (because of the loop?)
}    
});

and this (second) code saves the json array to an external file:

fs.writeFile('example.json', JSON.stringify(dataObj, null, 4);

The quistion is how to put the second codes into the first code (combine them)?



from csvtojson node.js (combine two codes)

No comments:

Post a Comment