0

Find string and delete line - Node.JS

var fs = require('fs')

fs.readFile('shuffle.txt', {encoding: 'utf-8'}, function(err, data) {
  if (err) throw error;

  let dataArray = data.split('\n'); // convert file data in an array
  const searchKeyword = 'user1'; // we are looking for a line, contains,       key word 'user1' in the file
  let lastIndex = -1; // let say, we have not found the keyword

  for (let index=0; index<dataArray.length; index++) {
    if (dataArray[index].includes(searchKeyword)) { // check if a line    contains the 'user1' keyword
      lastIndex = index; // found a line includes a 'user1' keyword
      break; 
    }
  }

  dataArray.splice(lastIndex, 1); // remove the keyword 'user1' from the data Array

  // UPDATE FILE WITH NEW DATA
  // IN CASE YOU WANT TO UPDATE THE CONTENT IN YOUR FILE
  // THIS WILL REMOVE THE LINE CONTAINS 'user1' IN YOUR shuffle.txt FILE
  const updatedData = dataArray.join('\n');
  fs.writeFile('shuffle.txt', updatedData, (err) => {
    if (err) throw err;
    console.log ('Successfully updated the file data');
  });

});

This link explains how to find a string and delete lines but only delete one user1 at the time. I have many lines with user1, how can I delete all:

john
doe
some keyword
user1
last word
user1
user1

Also the opposite. How can I delete all the lines and leave only the user1 lines?

1 Answers1

0

I would make use of the Array.filter() function.

Basically, you call filter() on an array, and define a callback function that checks every item of that array.

If the checking function returns true for a particular item, keep that item - put it in a new array If the checking function returns false, do not put the item in the new array

So, in your case, once you have read all the lines into an array (up to line 6 in your code), use the filter function:

// Delete all instances of user1
let newDataArray = dataArray.filter(line => line !== "user1")
// Delete everything except user1
let newDataArray = dataArray.filter(line => line === "user1")
// Delete any lines that have the text 'user1' somewhere inside them
let newDataArray = dataArray.filter(line => !line.includes("user1"))

Then, just like you have done in your code, use the join() function on newDataArray() and write the file.


To rewrite your code,

var fs = require('fs')

fs.readFile('shuffle.txt', {encoding: 'utf-8'}, function(err, data) {
  if (err) throw error;

  let dataArray = data.split('\n'); // convert file data in an array
  const searchKeyword = 'user1'; // we are looking for a line, contains,       key word 'user1' in the file

  // Delete all instances of user1
  let newDataArray = dataArray.filter(line => line !== searchKeyword)

  // UPDATE FILE WITH NEW DATA
  const updatedData = newDataArray.join('\n');

  fs.writeFile('shuffle.txt', updatedData, (err) => {
    if (err) throw err;
    console.log ('Successfully updated the file data');
  });

});