0

How to i can remove string from text file ?

fs.readFile('./banlist.txt', function read(err, data) {
                if (err) {
                    throw err;
                }
                lastIndex = function(){
                    for (var i = data_array.length - 1; i > -1; i--) 
                    if (data_array[i].match(ip))
                        return i;
                }()
                delete data_array[lastIndex];
            });

But console give me message: data_array is not defined. I want to remove ip adress line.

  • Where do you define `data_array`? I don't see it in this code snippet. – Adam P Jun 25 '18 at 23:53
  • everything in a text file is a string. and also `fs.readFile` does not populate data as an array, secondly strings are immutables. The delete key word only works on the members of an object. `data_array` is not defined any where. Check the arguments in your function if they are correct – 0.sh Jun 25 '18 at 23:56
  • you probably need to re-write the whole thing without that string. – Liang Jun 25 '18 at 23:59
  • Read the file, modify the data, then rewrite the file? (if it's a reasonable size...) – Chris Jun 26 '18 at 00:23
  • If it is not too big: `var newData = data.toString().split('\n').filter(val=>val!==ip).join('\n')` and then write newData (string) back to the file. – Chris Jun 26 '18 at 00:25

1 Answers1

3

Your code seems overly complicated. The biggest problem is that data_array doesn't exist, and data isn't an array. The simplest solution (though synchronous, which might be slow if you're dealing with a large file) is below:

var data = fs.readFileSync('banlist.txt', 'utf-8');
var ip = "STRING_TO_REMOVE";

var newValue = data.replace(new RegEx(ip), '');
fs.writeFileSync('banlist.txt', newValue, 'utf-8');

This will remove the first occurrence of the specified string from anywhere in the file. This means that if you're searching for "foo" and your file contains "This is foobar." it will end up as "This is bar.". If you have items on separate lines and want to remove any items that match, please clarify that in your question.

The above was adapted from this answer.

Matthias
  • 648
  • 6
  • 18
  • I can't think of any reason why it would create spaces. If you mean that it doesn't remove spaces, that's intentional. You can add spaces to the removal string in order to remove spaces. If you're looking for more complicated searches (such as removing space only if it's there), you can replace `new RegEx(ip)` with a regular expression, as explained [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or ask another question. – Matthias Jun 26 '18 at 05:35