Reputation: 37
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.
Upvotes: 0
Views: 9334
Reputation: 707
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.
Upvotes: 3