Deviopath › Node.js

Glob Pattern Matching

Hard · Tooling

Node.js tools (npm's files field, ESLint, test runners, fs.glob) select files with glob patterns. Write globMatch(pattern, path) that returns true if a relative, /-separated path matches the pattern.

- First expand braces: {a,b} means either alternative, so *.{js,ts} is *.js or *.ts. Braces can be nested and may contain /. They always contain at least one comma.

- Then compare segment by segment (split on /).

- A segment that is exactly ** matches zero or more whole segments.

- Inside a segment: * matches any run of characters (also none), ? exactly one character, [abc] one of the listed characters, [a-z] a character in the range, and [!a-c] any character not listed. Every other character matches itself (. is not special). ** inside a longer segment (like a**b) acts like *.

- Dotfiles: a path segment starting with . can only be matched by a pattern segment that starts with a literal .. So *, ?, [...] and ** never match a leading dot.

The driver filterPaths(pattern, paths) is already written and returns the matching paths in order.

These rules are a simplified version of what the minimatch package does. Real tools differ in small details (for example whether src/** matches src itself); the tests do not depend on those.

Next: Incremental HTTP Request Parser