Skip to content

Instantly share code, notes, and snippets.

@zkliu611
Created April 6, 2019 02:12
Show Gist options
  • Save zkliu611/5aa37dc84741b0702e7d603c7b22539f to your computer and use it in GitHub Desktop.
Save zkliu611/5aa37dc84741b0702e7d603c7b22539f to your computer and use it in GitHub Desktop.
#!/usr/local/bin/node
const fs = require('fs');
function findFiles(filePath) {
// iterate through each files to find query
// for each files, split text files by line into an array
// iterate through array to find query
// if query is found, add files path + text line num + /t + text to results
// if additional folder are inside path
// call findFiles on the folder path to check all files inside this folder.
let files = fs.readdirSync(filePath) // get all files from current folder
let retVal = [];
for (let i = 0; i < files.length; i++) { // iterate through the files and search for query str.
if (files[i].includes('.txt')){
let currentFilePath = filePath + '/' + files[i]; // path to one of the file
retVal.push(currentFilePath);
} else { // if not text file, recusively call findFiles on the folder
let children = findFiles(filePath + '/' + files[i]);
if (children) {
children.forEach((file) => {
retVal.push(file);
})
}
}
}
return retVal;
}
function doSearch(files, str) {
let result = [];
files.forEach((file) => {
let res = fs.readFileSync(file, 'utf8');
let arr = res.split('\n')
for (let j = 0; j < arr.length; j++) {
if (arr[j].includes(str)) {
result.push(file + ':' + j+1 + '\t' + arr[j]);
}
}
});
console.log(result.join("\n"));
}
function mygrep(str, path) {
//recurisve check all files in the folder.
let files = findFiles(path);
doSearch(files, str);
}
if (process.argv.length < 4) {
console.log('Requires at lease 2 arguments');
}
else {
mygrep(process.argv[2], process.argv[3]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment