find matches in files and parse out the line number - node.js

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);
}

Related

Issue with filestream, reading line by line. ENONET thrown, despite file existing

I'm having issues with a function that reads a text file line by line. It says the file I'm trying to read does not exist, although it does in the file path I am running node on. What could be the issue??
function insertUsers(auth) {
fs.readFile('emails.txt', function (err, data) {
if (err) throw err;
var person = data.toString().split("\n");
var person = data.toString().split("\n");
for (var i = 0; i < person.length(); i++) {
service.members.insert({
groupKey: 'testgroup#x.com',
resource: {
email: person[i],
role: 'MEMBER',
}
}, (err, res) => {
if (err) { return console.error('The API returned an error:', err.message); }
const user = res.data.member;
if (member.length) {
write_log('Inserted' + email + ' into student group.');
} else {
write_log('Failed to delete ' + email);
}
});
}
});
}
https://i.stack.imgur.com/5UTK6.png and https://i.stack.imgur.com/iVvnA.png
Verify that you're starting your node application from the same location where your file (emails.txt) is. According to your method logic it should be
C:\Users\[]\source\repos\StudentGroups\StudentGroups > node main.js
you can check the current working directory from the code
console.log(process.cwd())
it should be
C:\Users\[]\source\repos\StudentGroups\StudentGroups
Otherwise, modify your code to correctly point to the email.txt or start your application from the correct directory.
This problem was due to how I made emails.txt. The name is "emails.txt", and the file extension is .txt. I changed the file name to "emails", and it worked.

nodejs create directory in sync way is not reliable

I am using following code to create directories in sync way. It checks the existence of the directory, deletes it if exists and creates it. All operations are in sync way. I am looping this operation for 5 times. I am getting different results each time. Sometimes it creates only 4 directories, sometimes it creates all 5. What is the reason for this unstability in the code?
fs.readdir(dir, function(err, filenames) {
if (err) {
onError(err);
return;
}
filenames.forEach(function(filename) {
fs.readFile(dir + filename, 'utf-8', function(err, content) {
if (err) {
onError(err);
return;
}
AsyncFunc(content, ....)
.then(newContent => {
filenames.forEach(function(filename) {
if (fs.existsSync(currentDirName)) {
fs.rmdirSync(currentDirName);
}
fs.mkdirSync(currentDirName, '0766');
});
});
});
If you are using sync functions you can not use callbacks. Also if you want to remove a folder you need to use rmdirSync(filename);
var fs = require('fs');
var filenames = ['1','2','3','4'];
filenames.forEach(function(filename) {
if (fs.existsSync(filename)) {
fs.rmdirSync(filename);
}
fs.mkdirSync(filename, '0766');
});

In nodejs how to read a file and move it to another folder if the file contains a specified text

So I have the following code
var processed;
fs.readFile(path, 'utf-8', function(err, data) {
processed = false;
//checking if text is in file and setting flag
processed = true;
});
if (processed == true) {
try {
var fname = path.substring(path.lastIndexOf("\\") + 1);
fs.moveSync(path, './processedxml/' + fname, {
overwrite: true
})
} catch (err) {
console.log("Error while moving file to processed folder " + err);
}
}
But I don't get the desired output. Because looks like the readfile is executed by a separate thread and so the value of "processed" is not reliable.
I am not very familiar with nodejs so any help will be greatly appreciated.
Yes, you are right, your executions are performed by different threads.
In this scenario, you'll need to use promises.
You can solve your need easily by using "Promise FS" (you can use any other promise solution anyway).
Your code would be something like the following:
fs = require('promise-fs');
var fname = 'test.txt' ;
var toMove = false ;
fs.readFile('test.txt','utf8')
.then (function (content) {
if(content.indexOf('is VALID') !== -1) {
console.log('pattern found!');
toMove = true ;
}
else { toMove = false
}
return toMove ;
}).
then (function (toMove) {
if(toMove) {
var oldPath = 'test.txt'
var newPath = '/tmp/moved/file.txt'
fs.rename(oldPath, newPath, function (err) {
if (err) throw err
console.log('Successfully renamed - moved!')
}) ;
}
})
.catch (function (err) {
console.log(err);
})
Create a file "test.txt" and add the following contents:
this is text.file contents
token is VALID
The code above will evaluate if "is VALID" is present as content and if it does then it will move the file "test.txt" from your current folder to a new one called "moved" in "/tmp" directory. It will also rename the file as "file.txt" file name.
Hope it helps you.
Regards
It looks like you're shadowing path, trying to use it as a variable and as a node module. The easiest way to make this work is to choose a different variable name for the file and move the processing logic into the callback of fs.readFile.
var path = require('path');
var fs = require('fs-extra');
var file = 'some/file/path/foo.xml';
var text = 'search text';
fs.readFile(file, 'utf-8', function (err, data) {
if (err) {
console.error(err);
} else {
//checking if text is in file and setting flag
if (data.indexOf(text) > -1) {
try {
var fname = path.basename(file);
fs.moveSync(file, './processedxml/' + fname, {
overwrite: true
})
} catch (err) {
console.log("Error while moving file to processed folder " + err);
}
}
}
});

How to read records in a file, one by one

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);
});

Different results from asynchronous and synchronous reading

I have a fairly simple script that attempts to read and then parse a JSON file. The JSON is very simple and I am pretty sure it is valid.
{
"foo": "bar"
}
Now, I have been trying to read it with fs.readFile. When read no errors occur and the returned data is a string. The only problem is that the string is empty.
I repeated my code but used fs.readFileSync, this returned the file perfectly using the same path. Both had a utf-8 encoding specified.
It is very simple code, as you can see.
fs.readFile('./some/path/file.json', 'utf8', function(err, data) {
if(!err) {
console.log(data); // Empty string...
}
});
console.log(fs.readFileSync('./some/path/file.json', 'utf8')); // Displays JSON file
Could it be permissions or ownership? I have tried a permission set of 755 and 777 to no avail.
I am running node v0.4.10. Any suggestions to point me in the right direction will be much appreciated. Thanks.
Edit: Here is a block of my actual code. Hopefully this will give you a better idea.
// Make sure the file is okay
fs.stat(file, function(err, stats) {
if(!err && stats.isFile()) {
// It is okay. Now load the file
fs.readFile(file, 'utf-8', function(readErr, data) {
if(!readErr && data) {
// File loaded!
// Now attempt to parse the config
try {
parsedConfig = JSON.parse(data);
self.mergeConfig(parsedConfig);
// The config was loaded and merged
// We can now call the callback
// Pass the error as null
callback.call(self, null);
// Share the news about the new config
self.emit('configLoaded', file, parsedConfig, data);
}
catch(e) {
callback.call(self, new Error(file + ': The config file is not valid JSON.'));
}
}
else {
callback.call(self, new Error(file + ': The config file could not be read.'));
}
});
}
else {
callback.call(self, new Error(file + ': The config file does not exist.'));
}
});
This is pretty weird.
The code looks.
var fs = require('fs');
fs.readFile('./jsonfile', 'utf8', function(err, data) {
if(err) {
console.error(err);
} else {
console.log(data);
parsedConfig = JSON.parse(data);
console.log(parsedConfig);
console.log(parsedConfig.foo);
}
});
Json file:
{
"foo": "bar"
}
output :
$ node test_node3.js
{
"foo": "bar"
}
{ foo: 'bar' }
bar
This is on node 0.4.10 , but i'm pretty sure it should work on all node version.
So why your data is empty ? You should check err in this case (like mine) and post the output if any. If you have no error, you may fill a bug on github

Resources