Ashish Choubey
Ashish Choubey

Reputation: 457

How to add extra line on first line of CSV file and also insert "," but not split in new rows while CSV generation and remove it while processing back

I am using two node packages json2csv for CSV generation and csvtojson for converting back csv to json.

My use case is I am trying to add instruction on first line of CSV file while generating the CSV file and I would have to remove the exact first line when I am processing back the CSV file.

For eg:-

While generating CSV file let's say I prepared a JSON

import { Parser } from "json2csv";
const json = [{"name": "foo","age": 22}, {"name": "bar","age": 23}];
const introductionText = `Please follow these instruction \n
 1. instruction 1, Do some activity \n
 2. instruction 2, Do something else \n
 3. instruction 3 \n
`
const json2csvParser = new Parser();
const generatedCsv = json2csvParser.parse(json);
const newCsv = introductionText + generatedCsv;

The issue is when I concatenate the string to new CSV it adds the instruction text to CSV file but all the instruction 1, 2, 3 comes in next row. I want all the instruction to be only in first row only. How can I achieve that. I tried \n , \r\n nothing works.

Currently I added special code like \u2028 to introduce the new line but I feel that might not be correct.

I haven't figured out how can I add commas in text. Whenever I add it the text goes in next row. How can I add commas in cell with without adding a new row.

My second question how can I remove the same introduction text first and then pass it to csvtojson module.

I have written the code like this While converting back CSV to JSON

import * as csv from "csvtojson";
const csvStringWithIntruction = buffer.toString(); 
let csvStringWithoutInstruction;
if (isStringAndNotEmpty(csvStringWithIntruction)) {
   csvStringWithoutInstruction = csvStringWithIntruction.replace(/^"?\s*Please.+instruction\s*2\s*"?,*/gms, "").trim();
}
const stream = new Readable();
stream.push(csvStringWithoutInstruction);
stream.push(null);
cont jsonData = await convertCSVToJSONFromStream(stream);



async function convertCSVToJSONFromStream(readStream: Fs.ReadStream | Readable) {
    return csv.default()
        .fromStream(readStream)
        .subscribe((json) => {
            return new Promise((resolve,reject)=>{
                resolve(json);
            });
        }, onCSVParseError);
}

I am getting proper json data but it fails if the file is prepared from google sheet or some other source. It only works if someone has downloaded the file which I have prepared. How can I avoid this and can you suggest If there is a better approach to do this

Upvotes: 0

Views: 1323

Answers (0)

Related Questions