I am reading a book called Node.js in Action by Nike Cantelon and stuck at a configurable logger implementation:
when using String.prototype.replace() we set a function(match, property) as a second parameter and I am clueless about what it does . Could anyone explain what function(match, property) does? The way code is written doesn't give me an insight into that..
function setup(format){
let regex = /:(\w+)/g;
return function logger(req, res, next){
let str = format.replace(regex, (match, property) => {
return req[property];
});
console.log(str);
next();
}
}
module.exports = setup;
The String.replace() function takes two arguments: searchvalue
and newvalue
. This means that you are searching for a particular pattern in your format
string. When found, it is replaced by the value of req[property]
. So the function is getting the property
as it's argument, then uses it as a key for req
object, getting the value back and replacing the found appearance in format
string.
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.