Dhanan Dhanan - 3 months ago 12
Javascript Question

Regular expression to match exact same block

Please help me to find out a specific text included block from this file.
I'm reading context using Node js fs.

<VirtualHost *:80>
DocumentRoot /home/site1
ServerName www.site1.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /home/site2
ServerName www.site2.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /home/site3
ServerName www.site3.com
</VirtualHost>


Code:

fileContext.toString().split("\n");
var matched = fileContext.toString().replace( /<VirtualHost[\s\S]*?<\/VirtualHost>/gm,"--matched--" );


above code is working fine but it will match all vhost blocks.
I only needs to find vhost block which is contain "www.site2.com"

Answer

After some deliberation, I've come to the conclusion that regex isn't going to cut the mustard. I'd recommend using node-apacheconf.

var name = "www.site2.com";

apacheconf('/etc/apache2/httpd.conf', function(err, config, parser) {
  if (err) throw err

  console.log(config.VirtualHost.filter(function(vh) {
    return vh.ServerName == name;
  }));
});
Comments