Search code examples
javascriptnode.jsfile-read

Matching two strings stored in different variables in nodejs


I am new to node.js. I was practising a program to find a pattern in a string and extracting that part of line from the file. File as:

Something written in a file saved as filename.ext.
At a line, it contains a link.
import "https:\//www.hostname.com/$path"

I want to extract the link from any line in a file. I was trying to match the pattern to get index no of 'h' in 'http' and extracting it further. Stuck at nm() as it isn't working on variable as parameter.

var url=require('url')
var fs = require('fs');
var find = require('find');
var findInFiles = require('find-in-files');
var LineReader = require('linereader');
var nm = require('nanomatch');
var sol=require('./../bin/sol-merger')
var dir = './merged/';
var pth=process.cwd()+'/'+dir+'newfile.sol'
var flag=0
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
fs.createReadStream(sol.abs_path).pipe(fs.createWriteStream(dir+'/newfile.sol'));

findInFiles.find({'term': "http", 'flags': 'ig'}, 'merged/', '.sol$').then(function(results) {
//console.log("here...")
for (var result in results) {
    var res = results[result];
    console.log('found "' + res.matches[0] + '" ' + res.count+ ' times in "' + result + '"')
    console.log(sol.fl+"    "+result)   
}
var lr=new LineReader(pth)
lr.on('error', function (err) {
    console.log(err);
    console.log("error")
    lr.close();
});
lr.on('line', function (lineno, line) {
    console.log(lineno + "   " + line);
    if(nm.contains(`$line`,'*"http**"*')){
        console.log("found")
    }
});
})

Solution

  • Change

    findInFiles.find({'term': "http", 'flags': 'ig'}, 'merged/', '.sol$')
    

    to

    var regex = 'http.*?(?=\")'
    findInFiles.find({term: regex, flags: 'g'}, 'merged/', '.sol$')
    

    The regex matches http/https link till " is found at end of link, but doesn't capture " in group. (?=\") is positive lookahead match.

    See regular expression's explanation and working example here - https://regex101.com/r/4RAr0Z/1