How to read file, search for string and delete line in node.js? I have tried
var fs = require('fs')
fs.readFile('shuffle.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('user1'))
return i;
}()
delete data_array[lastIndex];
});
Let's say we have a text file, shuffle.txt contains the following content
john
doe
user1
some keyword
last word
Now we read the shuffle.txt file and then search for 'user1' keyword. If any line contains the 'user1', then we will remove the line.
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');
});
});
Here, if a line contains 'user1' keyword, we are removing the entire line. The new shuffle.txt file will be no longer contains a line with 'user1' keyword. The updated shuffle.txt file looks like
john
doe
some keyword
last word
For more information check the doc.
Related
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?
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');
});
});
I am trying to find matches in files and parse out the line number and what was the match along with the file name. So far I am able to read the files from the directory / sub directories and then use indexOf() which in this case is not very efficient. The goal would be go through all the files and find matches for the following
.http(
.httpContinue(
$httpUrl(
httpURL
getHttpImageURL(
getHttpURL(
The code I have so far looks like this
var fs = require('fs');
var path = [my directory];
function readFiles(dirname) {
fs.readdir(dirname, function(err, filenames) {
if (err) {
return;
}
filenames.forEach(function(filename) {
if (fs.lstatSync(dirname+'/'+filename).isDirectory() ){
readFiles(dirname+'/'+filename);
};
fs.readFile(dirname+'/'+filename, { encoding: 'utf8' }, function(err, content) {
if (err) {
return;
}
//This is not very effective and I need to check each line for all these possible matches
if (content.indexOf('http(') > -1) {
if(err) {
return console.log(err);
}
console.log(filename);
}
});
});
});
}
readFiles(path);
The challenge I am facing is to read lines and parse line numbers where I found a match and what was the match. Cant figure out how to accomplish that.
You could try this for your if statement
// This should really go somewhere near the top of the file
const wantedStrings = ['.http(',
'.httpContinue(',
'$httpUrl(',
'httpURL',
'getHttpImageURL(',
'getHttpURL('];
if (content.toLowerCase().includes('http')
&& wantedStrings.filter(s => content.includes(s)).length > 0) {
// Don't need another err check here
console.log(filename);
}
I want to read line by line file and compare with value in a object that where passed to my function. Unfortunately I get information that object is undefined but when I checked it showed me correct data. This is code
module.exports = function savefile(pathname, changesvalue){
var counter = 0;
var i = 0;
var message = [];
var test = changesvalue[i].seekrange; //here I have correct information
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(pathname)
});
lineReader.on('line', function (line) {
if(counter == parseInt(changesvalue[i].seekrange)){ //here it showed that value is undefind
var textadd = changesvalue[i].seektext.match(/([a-zA-Z-/]+)/g);
message.push(' ' + textadd[0] + ' ' + changesvalue[i].seekvalue + textadd[1]);
i++;
}
else{
console.log(line);
}
counter++;
});
lineReader.on('end', function () {
fs.writeFile('file_to_save_to', message, function(err) {
if (err) {
return console.log(err);
}
});
}
};
I don't now exactly why I get undefined? And how to processes this file in efficient way to read file, change some line and write to file?
Thank you for your help
I have the following text file ("test.txt") that I want to manipulate in node.js:
world
food
I want to remove the first line so that food becomes the first line instead. How can I do that?
var fs = require('fs')
fs.readFile(filename, 'utf8', function(err, data)
{
if (err)
{
// check and handle err
}
// data is the file contents as a single unified string
// .split('\n') splits it at each new-line character and all splits are aggregated into an array (i.e. turns it into an array of lines)
// .slice(1) returns a view into that array starting at the second entry from the front (i.e. the first element, but slice is zero-indexed so the "first" is really the "second")
// .join() takes that array and re-concatenates it into a string
var linesExceptFirst = data.split('\n').slice(1).join('\n');
fs.writeFile(filename, linesExceptFirst, function(err, data) { if (err) {/** check and handle err */} });
});
I just came across the need to be able to exclude several lines in a file. Here's how I did it with a simple node function.
const fs = require('fs');
const removeLines = (data, lines = []) => {
return data
.split('\n')
.filter((val, idx) => lines.indexOf(idx) === -1)
.join('\n');
}
fs.readFile(fileName, 'utf8', (err, data) => {
if (err) throw err;
// remove the first line and the 5th and 6th lines in the file
fs.writeFile(fileName, removeLines(data, [0, 4, 5]), 'utf8', function(err) {
if (err) throw err;
console.log("the lines have been removed.");
});
})
use replace
const fs = require('fs');
function readWriteSync() {
var data = fs.readFileSync(filepath, 'utf-8');
// replace 'world' together with the new line character with empty
var newValue = data.replace(/world\n/, '');
fs.writeFileSync(filepath, newValue, 'utf-8');
}
I have a text file with multiple JSON documents on it, the JSON docs are not separated by new lines but instead they are separated by two new lines and a custom tag something like this
\n
#RECORD#SEPARATOR#
\n
What is the best way to read one by one on a stream, I am a complete node beginner and want to find the best way to do this.
Try something like this:
'use strict';
var fs = require('fs');
fs.readFile('yourfile.txt', function(err, data) {
if (err) {
throw err;
}
var docs = (data
.toString()
.split('\n')
.filter(function(line) {
return line.trim() !== '';
})
.map(function(line) {
// Do something else here depending on the exact format of your data
return 'A non-empty line: ' + line;
})
);
console.log(docs);
});