简体   繁体   中英

how am I supposed to understand this code? Node.js

I've been currently studying on MEAN stack to be an web programmer, I was stuck in this code, which I couldn't even guess at all. Can someone please tell me what this means and where this is from?

http.createServer(function(req, res){
  var _url;

  ....

  if(_url = /^\/employees$/i.exec(req.url)){
    res.writeHead(200);
    return res.end('employee list');
  }else if(_url = /^\/employees\/(\d+)$/i.exec(req.url)){
    res.writeHead(200);
    return res.end('a single employee');
  }else{
    res.writeHead(200);
    res.end('static file maybe');
  }
});

So, what I want to know is these parts below:

  • _url = /^/employees$/i.exec(req.url)
  • _url = /^/employees/(\\d+)$/i.exec(req.url)

^\\/employees$

^ - Begins with
\/ - Escaped '/'. (i.e. begins with '/')
employees - contains employees.
$ - ends with (i.e. finally, it'll only match '/employees')

^\\/employees\\/(\\d+)$

Here, the (\\d+) is a group where:

\d - matches digits (0-9)

+ - one or more previous token (i.e. matches 012345 or 1234 or 23, etc. but not blank or string).

the /^\\/employees$/i is a regex that is checking if the request url includes the string /employees without anything after

if a match was found _url will be a string (a truthy value), otherwise it will be null (a falsy value)

_url = /^/employees/(\\d+)$/i.exec(req.url) is looking for /employees/NUMBER

^ means beginning of string

\\/ is escaping /

employees is a literal string

\\d means any digit

$ means end of string

i means not case sensitive (both EmPlOyeeS and employees will match the same)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM