How to append data based on a condition inn file using Nodejs

41 Views Asked by At

I have a file. I need to append an annotation ( @Circuit(name = backendB) ) if "createEvent" name exists and annotation is not present in that file. I'm not sure how to proceed further. Can anyone help me what is the way to check and append using streams.

async function appendData() {
  let file_path = "./File/controller.java"

  try {
    let txt = "( @Circuit(name = backendB) )"
    
    const readstream = fs.createReadStream(file_path);
    const updtstrem = fs.createWriteStream("./FileUpload/auditcontroller_test.java")

    readstream
      .on("data", (data) => {
        let temp = data.toString()

        let pos = temp.toString().indexOf("createEvent")
      })
  }
}
1

There are 1 best solutions below

0
On BEST ANSWER

There is a term called "readline". You could use that.

const fs = require('fs');
const readline = require('readline');

async function appendData() {
  const file_path = './File/controller.java';
  const output_path = './FileUpload/auditcontroller_test.java';
  const annotation = '@Circuit(name = backendB)';

  const readstream = fs.createReadStream(file_path);
  const writestream = fs.createWriteStream(output_path);
  const rl = readline.createInterface({
    input: readstream,
    crlfDelay: Infinity,
  });

  let annotationAdded = false;

  for await (const line of rl) {
    let updatedLine = line;

    if (line.includes('createEvent') && !line.includes(annotation)) {
      updatedLine = line.replace(
        /(createEvent)/,
        `$1 ${annotation}`
      );
      annotationAdded = true;
    }

    writestream.write(updatedLine + '\n');
  }

  if (!annotationAdded) {
    writestream.write(`${annotation}\n`);
  }

  readstream.close();
  writestream.close();
}

// Call the function
appendData();

This should work I think. Do let me know if stuck.