Alexander Mills
Alexander Mills

Reputation: 100000

Regular expression in Express 4 to capture all requests to static assets for file extension .gz

I am looking to do something like this:

app.get('*.gz',function(req,res,next){

  res.set('Content-Encoding','gzip');
  next();

});

but I don't think the regex I am using is correct. As the example suggests, I am looking for middleware that captures all requests to static assets that have an extension of .gz. (.gz being files zipped by gzip). Is my example correct?

Also if someone could mention what type of regular expressions Expess uses, that would help me look up reference material. To date, I have never read anywhere whether they are standard JS regexp's or Perl style or what?

Upvotes: 2

Views: 1481

Answers (3)

Renae Lider
Renae Lider

Reputation: 1024

(.*)\.gz$

This will capture the filename without the extension. If you need the extension move the closing parenthesis to the right of gz. This might give you some false positives depending on your data structure - which you haven't mentioned in the question, btw. This will avoid any filenames that looks like this: filename.gz.tar.

Here's a breakdown of the code from regex101.com:

1st Capturing group (.*)
    .* matches any character (except newline)
        Quantifier: * Between zero and unlimited times, 
        as many times as possible, giving back as needed [greedy]
\. matches the character . literally
gz matches the characters gz literally (case sensitive)
$ assert position at end of the string
g modifier: global. All matches (don't return on first match)

Upvotes: 1

S.aad
S.aad

Reputation: 538

The regular expression would be '.*\.gz' to get all file names with the extension .gz

I have worked with front end js a little and the regex were closed in back slashes rather than single quotes. Please check if this is the right way to input regex.

You are currently using wildcard "*" technique. Various language do support this for example VB(Visual Basic) i would do exactly what you are doing when selecting files with the same extension.

Upvotes: 0

cshion
cshion

Reputation: 1213

I think you could try app.use instead app.get and check if static file youre looking for is correct , something like this

app.use("*.gz" , function(req,res,next){
    console.log(req.originalUrl);
    next();
}

You have to put this code before serve static files ( app.use(express.static(...) )

Upvotes: 1

Related Questions