admin管理员组文章数量:1415140
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.
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.
Share Improve this question asked Jun 25, 2018 at 23:51 Yavuz Selim ÖzmenYavuz Selim Özmen 372 silver badges9 bronze badges 5-
Where do you define
data_array
? I don't see it in this code snippet. – Adam P Commented Jun 25, 2018 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 Commented Jun 25, 2018 at 23:56 - you probably need to re-write the whole thing without that string. – Liang Commented Jun 25, 2018 at 23:59
- Read the file, modify the data, then rewrite the file? (if it's a reasonable size...) – Chris Commented Jun 26, 2018 at 0: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 Commented Jun 26, 2018 at 0:25
1 Answer
Reset to default 3Your code seems overly plicated. 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.
本文标签: javascriptNode jsRemove string from text fileStack Overflow
版权声明:本文标题:javascript - Node js - Remove string from text file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745228083a2648700.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论