I have:
let removeString = (fileName, strToRemove) => {
fs.readFile(fileName, 'utf8', function(err, data){
let toRemove = data.replace(strToRemove+'\n','')
fs.writeFile(fileName, toRemove)
})
};
This successfully removes non first or last line, but how do I remove from
first
second
third
First
or third
using fs?
I have:
let removeString = (fileName, strToRemove) => {
fs.readFile(fileName, 'utf8', function(err, data){
let toRemove = data.replace(strToRemove+'\n','')
fs.writeFile(fileName, toRemove)
})
};
This successfully removes non first or last line, but how do I remove from
first
second
third
First
or third
using fs?
- I have tried your code and it did remove 'first' when calling removeString('file.txt', 'first'). – Enric A. Commented May 9, 2018 at 10:45
- 1 Suspiciously similar question, but a different account ..? – Teemu Commented May 9, 2018 at 10:51
- @Teemu and that one again looks like a duplicate of stackoverflow./q/50237509/1427878 ... – C3roe Commented May 9, 2018 at 11:15
- @CBroe Indeed, all the questions were including a "[tag]" in the title too ... – Teemu Commented May 9, 2018 at 11:22
- ... I saw [tag] in other questions – ImFaind Commented May 9, 2018 at 11:28
2 Answers
Reset to default 3The above solution is not optimized for a very large file as it reads the whole file. If you are on non-windows platform, you can run unix tail mand. If on windows, you can look at read-last-lines.
Look at this excellent answer
You can use split
to split the file into an array of lines then remove whichever line you want, then rejoin the array into a string using join
then write the file.
Example:
let removeString = (fileName, strToRemove) => {
fs.readFile(fileName, 'utf8', function(err, data){
let splitArray = data.split('\n');
splitArray.splice(splitArray.indexOf(strToRemove), 1);
let result = splitArray.join('\n');
fs.writeFile(fileName, result)
})
};