[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/)

**Fast, unopinionated, minimalist web framework for [Node.js](http://nodejs.org).**

**This project has a [Code of Conduct][].**

## Table of contents

* [Installation](#Installation)
* [Features](#Features)
* [Docs & Community](#docs--community)
* [Quick Start](#Quick-Start)
* [Running Tests](#Running-Tests)
* [Philosophy](#Philosophy)
* [Examples](#Examples)
* [Contributing to Express](#Contributing)
* [TC (Technical Committee)](#tc-technical-committee)
* [Triagers](#triagers)
* [License](#license)

[![NPM Version][npm-version-image]][npm-url]
[![NPM Install Size][npm-install-size-image]][npm-install-size-url]
[![NPM Downloads][npm-downloads-image]][npm-downloads-url]
[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]

```js
const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(3000)
```

## Installation

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/).

Before installing, [download and install Node.js](https://nodejs.org/en/download/).
Node.js 0.10 or higher is required.

If this is a brand new project, make sure to create a `package.json` first with
the [`npm init` command](https://docs.npmjs.com/creating-a-package-json-file).

Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```console
$ npm install express
```

Follow [our installing guide](http://expressjs.com/en/starter/installing.html)
for more information.

## Features

  * Robust routing
  * Focus on high performance
  * Super-high test coverage
  * HTTP helpers (redirection, caching, etc)
  * View system supporting 14+ template engines
  * Content negotiation
  * Executable for generating applications quickly

## Docs & Community

  * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)]
  * [#express](https://web.libera.chat/#express) on [Libera Chat](https://libera.chat) IRC
  * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules
  * Visit the [Wiki](https://github.com/expressjs/express/wiki)
  * [Google Group](https://groups.google.com/group/express-js) for discussion
  * [Gitter](https://gitter.im/expressjs/express) for support and discussion

**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x).

## Quick Start

  The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below:

  Install the executable. The executable's major version will match Express's:

```console
$ npm install -g express-generator@4
```

  Create the app:

```console
$ express /tmp/foo && cd /tmp/foo
```

  Install dependencies:

```console
$ npm install
```

  Start the server:

```console
$ npm start
```

  View the website at: http://localhost:3000

## Philosophy

  The Express philosophy is to provide small, robust tooling for HTTP servers, making
  it a great solution for single page applications, websites, hybrids, or public
  HTTP APIs.

  Express does not force you to use any specific ORM or template engine. With support for over
  14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js),
  you can quickly craft your perfect framework.

## Examples

  To view the examples, clone the Express repo and install the dependencies:

```console
$ git clone https://github.com/expressjs/express.git --depth 1
$ cd express
$ npm install
```

  Then run whichever example you want:

```console
$ node examples/content-negotiation
```

## Contributing

  [![Linux Build][github-actions-ci-image]][github-actions-ci-url]
  [![Windows Build][appveyor-image]][appveyor-url]
  [![Test Coverage][coveralls-image]][coveralls-url]

The Express.js project welcomes all constructive contributions. Contributions take many forms,
from code for bug fixes and enhancements, to additions and fixes to documentation, additional
tests, triaging incoming pull requests and issues, and more!

See the [Contributing Guide](Contributing.md) for more technical details on contributing.

### Security Issues

If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md).

### Running Tests

To run the test suite, first install the dependencies, then run `npm test`:

```console
$ npm install
$ npm test
```

## People

The original author of Express is [TJ Holowaychuk](https://github.com/tj)

[List of all contributors](https://github.com/expressjs/express/graphs/contributors)

### TC (Technical Committee)

* [UlisesGascon](https://github.com/UlisesGascon) - **Ulises Gascón** (he/him)
* [jonchurch](https://github.com/jonchurch) - **Jon Church**
* [wesleytodd](https://github.com/wesleytodd) - **Wes Todd**
* [LinusU](https://github.com/LinusU) - **Linus Unnebäck**
* [blakeembrey](https://github.com/blakeembrey) - **Blake Embrey**
* [sheplu](https://github.com/sheplu) - **Jean Burellier**
* [crandmck](https://github.com/crandmck) - **Rand McKinney**
* [ctcpip](https://github.com/ctcpip) - **Chris de Almeida**

TC emeriti members

#### TC emeriti members

  * [dougwilson](https://github.com/dougwilson) - **Douglas Wilson**
  * [hacksparrow](https://github.com/hacksparrow) - **Hage Yaapa**
  * [jonathanong](https://github.com/jonathanong) - **jongleberry**
  * [niftylettuce](https://github.com/niftylettuce) - **niftylettuce**
  * [troygoode](https://github.com/troygoode) - **Troy Goode**

### Triagers

* [aravindvnair99](https://github.com/aravindvnair99) - **Aravind Nair**
* [carpasse](https://github.com/carpasse) - **Carlos Serrano**
* [CBID2](https://github.com/CBID2) - **Christine Belzie**
* [enyoghasim](https://github.com/enyoghasim) - **David Enyoghasim**
* [UlisesGascon](https://github.com/UlisesGascon) - **Ulises Gascón** (he/him)
* [mertcanaltin](https://github.com/mertcanaltin) - **Mert Can Altin**
* [0ss](https://github.com/0ss) - **Salah**
* [import-brain](https://github.com/import-brain) - **Eric Cheng** (he/him)
* [3imed-jaberi](https://github.com/3imed-jaberi) - **Imed Jaberi**
* [dakshkhetan](https://github.com/dakshkhetan) - **Daksh Khetan** (he/him)
* [lucasraziel](https://github.com/lucasraziel) - **Lucas Soares Do Rego**
* [IamLizu](https://github.com/IamLizu) - **S M Mahmudul Hasan** (he/him)
* [Sushmeet](https://github.com/Sushmeet) - **Sushmeet Sunger**

Triagers emeriti members

#### Emeritus Triagers

  * [AuggieH](https://github.com/AuggieH) - **Auggie Hudak**
  * [G-Rath](https://github.com/G-Rath) - **Gareth Jones**
  * [MohammadXroid](https://github.com/MohammadXroid) - **Mohammad Ayashi**
  * [NawafSwe](https://github.com/NawafSwe) - **Nawaf Alsharqi**
  * [NotMoni](https://github.com/NotMoni) - **Moni**
  * [VigneshMurugan](https://github.com/VigneshMurugan) - **Vignesh Murugan**
  * [davidmashe](https://github.com/davidmashe) - **David Ashe**
  * [digitaIfabric](https://github.com/digitaIfabric) - **David**
  * [e-l-i-s-e](https://github.com/e-l-i-s-e) - **Elise Bonner**
  * [fed135](https://github.com/fed135) - **Frederic Charette**
  * [firmanJS](https://github.com/firmanJS) - **Firman Abdul Hakim**
  * [getspooky](https://github.com/getspooky) - **Yasser Ameur**
  * [ghinks](https://github.com/ghinks) - **Glenn**
  * [ghousemohamed](https://github.com/ghousemohamed) - **Ghouse Mohamed**
  * [gireeshpunathil](https://github.com/gireeshpunathil) - **Gireesh Punathil**
  * [jake32321](https://github.com/jake32321) - **Jake Reed**
  * [jonchurch](https://github.com/jonchurch) - **Jon Church**
  * [lekanikotun](https://github.com/lekanikotun) - **Troy Goode**
  * [marsonya](https://github.com/marsonya) - **Lekan Ikotun**
  * [mastermatt](https://github.com/mastermatt) - **Matt R. Wilson**
  * [maxakuru](https://github.com/maxakuru) - **Max Edell**
  * [mlrawlings](https://github.com/mlrawlings) - **Michael Rawlings**
  * [rodion-arr](https://github.com/rodion-arr) - **Rodion Abdurakhimov**
  * [sheplu](https://github.com/sheplu) - **Jean Burellier**
  * [tarunyadav1](https://github.com/tarunyadav1) - **Tarun yadav**
  * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe**

## License

  [MIT](LICENSE)

[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/express/master?label=windows
[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express
[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/express/master
[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master
[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/express/master?label=linux
[github-actions-ci-url]: https://github.com/expressjs/express/actions/workflows/ci.yml
[npm-downloads-image]: https://badgen.net/npm/dm/express
[npm-downloads-url]: https://npmcharts.com/compare/express?minimal=true
[npm-install-size-image]: https://badgen.net/packagephobia/install/express
[npm-install-size-url]: https://packagephobia.com/result?p=express
[npm-url]: https://npmjs.org/package/express
[npm-version-image]: https://badgen.net/npm/v/express
[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/express/badge
[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/express
[Code of Conduct]: https://github.com/expressjs/express/blob/master/Code-Of-Conduct.md

Perplexity style AI Search engine clone built with Gemini 2.0 Flash and Grounding


# Reproducing a build

## Clone version

```
git clone https://github.com/planttheidea/fast-equals.git
cd fast-equals
git checkout {version}
```

Replace `{version}` above with the appropriate package version. If you want to compare a version older than `1.6.2`, you'll need to use a commit hash directly.

## Install

```
yarn install
```

We use `yarn` for our package management, so to ensure that exact dependencies you should also use it.

## Build artifacts

```
yarn run build
```

**NOTE**: To get an exact checksum match with the versions released on npm, it may be necessary to change line endings. For example, on Linux you might run:

```
unix2dos dist/fast-equals.min.js
```

## Get checksum

```
sha256sum dist/fast-equals.min.js
```


# fast-equals CHANGELOG

## 5.0.1

### Bugfixes

- Fix reference to `metaOverride` in typings and documentation (holdover from temporary API in v5 beta)

## 5.0.0

### Breaking changes

#### `constructor` equality now required

To align with other implementations common in the community, but also to be more functionally correct, the two objects being compared now must have equal `constructor`s.

#### `Map` / `Set` comparisons no longer support IE11

In previous verisons, `.forEach()` was used to ensure that support for `Symbol` was not required, as IE11 did not have `Symbol` and therefore both `Map` and `Set` did not have iterator-based methods such as `.values()` or `.entries()`. Since IE11 is no longer a supported browser, and support for those methods is present in all browsers and Node for quite a while, the comparison has moved to use these methods. This results in a ~20% performance increase.

#### `createCustomEqual` contract has changed

To better facilitate strict comparisons, but also to allow for `meta` use separate from caching, the contract for `createCustomEqual` has changed. See the [README documentation](./README.md#createcustomequal) for more details, but froma high-level:

- `meta` is no longer passed through to equality comparators, but rather a general `state` object which contains `meta`
- `cache` now also lives on the `state` object, which allows for use of the `meta` property separate from but in parallel with the circular cache
- `equals` is now on `state`, which prevents the need to pass through the separate `isEqual` method for the equality comparator

#### `createCustomCircularEqual` has been removed

You can create a custom circular equality comparator through `createCustomEqual` now by providing `circular: true` to the options.

#### Custom `meta` values are no longer passed at callsite

To use `meta` properties for comparisons, they must be returned in a `createState` method.

#### Deep links have changed

If you were deep-linking into a specific asset type (ESM / CJS / UMD), they have changed location.

**NOTE**: You may no longer need to deep-link, as [the build resolution has improved](#better-build-system-resolution).

### Enhancements

#### New "strict" comparators available

The following new comparators are available:

- `strictDeepEqual`
- `strictShallowEqual`
- `strictCircularDeepEqual`
- `strictCircularShallowEqual`

This will perform the same comparisons as their non-strict counterparts, but will verify additional properties (non-enumerable properties on objects, keyed objects on `Array` / `Map` / `Set`) and that the descriptors for the properties align.

#### `TypedArray` support

Support for comparing all typed array values is now supported, and you can provide a custom comparator via the new `areTypedArraysEqual` option in the `createCustomEqual` configuration.

#### Better build system resolution

The library now leverages the `exports` property in the `package.json` to provide builds specific to your method of consumption (ESM / CommonJS / UMD). There is still a minified UMD version available if you want to use it instead.

#### `arePrimitiveWrappersEqual` option added to `createCustomEqual` configuration

If you want a custom comparator for primitive wrappers (`new Boolean()` / `new Number()` / `new String()`) it is now available.

## 4.0.3

- Remove unnecessary second strict equality check for objects in edge-case scenarios

## 4.0.2

- [#85](https://github.com/planttheidea/fast-equals/issues/85) - `createCustomCircularEqual` typing is incorrect

## 4.0.1

- [#81](https://github.com/planttheidea/fast-equals/issues/81) - Fix typing issues related to importing in `index.d.ts` file

## 4.0.0

### Breaking Changes

#### Certain ES2015 features are now required

In previous versions, there were automatic fallbacks for certain ES2015 features if they did not exist:

- [`RegExp.prototype.flags`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags)
- [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)

Due to the omnipresence of support in both browser and NodeJS, these have been deprecated. There is still an option if you require support for these legacy environments, however; see [`createCustomEqual`](./README.md#createcustomequal) and [`createCustomCircularEqual`](./README.md#createcustomcircularequal) for more details.

#### `createCustomEqual` contract has changed

To allow more flexibility and customizability for a variety of edge cases, `createCustomEqual` now allows override of specific type value comparisons in addition to the general comparator it did prior. See [the documentation](./README.md#createcustomequal) for more details.

### Enhancements

#### `createCustomCircularEqual` added

Like `createCustomEqual`, it will create a custom equality comparator, with the exception that it will handle circular references. See [the documentation](./README.md#createcustomcircularequal) for more details.

#### Cross-realm comparisons are now supported

Prior to `4.x.x.`, `instanceof` was used internally for checking of object classes, which only worked when comparing objects from the same [Realm](https://262.ecma-international.org/6.0/#sec-code-realms). This has changed to instead use an object's [StringTag](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag), which is not realm-specific.

#### TypeScript typings improved

For better typing in edge-case scenarios like custom comparators with `meta` values, typings have been refactored for accuracy and better narrow flow-through.

## 3.0.3

- Fix [#77](https://github.com/planttheidea/fast-equals/issues/73) - better circular object validation

## 3.0.2

- Fix [#73](https://github.com/planttheidea/fast-equals/issues/73) - support comparison of primitive wrappers
- [#76](https://github.com/planttheidea/fast-equals/pull/76) - improve speed and accuracy of `RegExp` comparison in modern environments

## 3.0.1

- Fix [#71](https://github.com/planttheidea/fast-equals/pull/71) - use generic types for better type flow-through

## 3.0.0

### Breaking changes

When creating a custom equality comparator via `createCustomEqual`, the equality method has an expanded contract:

```ts
// Before
type EqualityComparator = (objectA: any, objectB: any, meta: any) => boolean;

// After
type InternalEqualityComparator = (
  objectA: any,
  objectB: any,
  indexOrKeyA: any,
  indexOrKeyB: any,
  parentA: any,
  parentB: any,
  meta: any,
) => boolean;
```

If you have a custom equality comparator, you can ignore the differences by just passing additional `undefined` parameters, or you can use the parameters to further improve / clarify the logic.

- Add [#57](https://github.com/planttheidea/fast-equals/pull/57) - support additional metadata for custom equality comparators

## 2.0.4

- Fix [#58](https://github.com/planttheidea/fast-equals/issues/58) - duplicate entries in `Map` / `Set` can create false equality success
- [#60](https://github.com/planttheidea/fast-equals/issues/60) - Add documentation for key equality of `Map` being a part of `deepEqual`

## 2.0.3

- Fix [#50](https://github.com/planttheidea/fast-equals/pull/50) - copy-pasta in cacheable check

## 2.0.2

- Optimize iterables comparisons to not double-iterate
- Optimize loop-based comparisons for speed
- Improve cache handling in circular handlers
- Improve stability of memory by reducing variable instantiation

## 2.0.1

- Fix [#41](https://github.com/planttheidea/fast-equals/pull/41) - prevent `.rpt2_cache` directory from being published for better CI environment support (thanks [@herberttn](https://github.com/herberttn))

## 2.0.0

### Breaking changes

- There are longer `fast-equals/es`, `fast-equals/lib`, `fast-equals/mjs` locations
  - Instead, there are 3 builds in `dist` for different consumption types:
    - `fast-equals.js` (UMD / `browser`)
    - `fast-equals.esm.js` (ESM / `module`)
    - `fast-equals.cjs.js` (CommonJS / `main`)
- There is no default export anymore, only the previously-existing named exports
  - To get all into a namespace, use `import * as fe from 'fast-equals`

### Updates

- Rewritten completely in TypeScript
- Improve speed of `Map` / `Set` comparisons
- Improve speed of React element comparisons

### Fixes

- Consider pure objects (`Object.create(null)`) to be plain objects
- Fix typings for `createCustomEqual`

## 1.6.3

- Check the size of the iterable before converting to arrays

## 1.6.2

- Fix [#23](https://github.com/planttheidea/fast-equals/issues/23) - false positives for map
- Replace `uglify` with `terser`
- Use `rollup` to build all the distributables (`main`, `module`, and `browser`)
  - Maintain `lib` and `es` transpilations in case consumers were deep-linking

## 1.6.1

- Upgrade to `babel@7`
- Add `"sideEffects": false` to `package.json` for better tree-shaking in `webpack`

## 1.6.0

- Add ESM support for NodeJS with separate [`.mjs` extension](https://nodejs.org/api/esm.html) exports

## 1.5.3

- Fix `Map` / `Set` comparison to not require order to match to be equal

## 1.5.2

- Improve speed of object comparison through custom `hasKey` method

## 1.5.1

- Fix lack of support for `unicode` and `sticky` RegExp flag checks

## 1.5.0

- Add [`circularDeepEqual`](README.md#circulardeepequal) and [`circularShallowEqual`](README.md#circularshallowequal) methods
- Add `meta` third parameter to `comparator` calls, for use with `createCustomEqual` method

## 1.4.1

- Fix issue where `lastIndex` was not being tested on `RegExp` objects

## 1.4.0

- Add support for comparing promise-like objects (strict equality only)

## 1.3.1

- Make `react` comparison more accurate, and a touch faster

## 1.3.0

- Add support for deep-equal comparisons between `react` elements
- Add comparison with `react-fast-compare`
- Use `rollup` for `dist` file builds

## 1.2.1

- Fix errors from TypeScript typings in strict mode (thanks [@HitoriSensei](https://github.com/HitoriSensei))

## 1.2.0

- Surface `isSameValueZero` as [`sameValueZeroEqual`](#samevaluezeroequal) option

## 1.1.0

- Add TypeScript typings (thanks [@josh-sachs](https://github.com/josh-sachs))

## 1.0.6

- Support invalid date equality via `isSameValueZero`

## 1.0.5

- Replace `isStrictlyEqual` with `isSameValueZero` to ensure that `shallowEqual` accounts for `NaN` equality

## 1.0.4

- Only check values when comparing `Set` objects (improves performance of `Set` check by ~12%)

## 1.0.3

- Make `Map` and `Set` comparisons more explicit

## 1.0.2

- Fix symmetrical comparison of iterables
- Reduce footprint

## 1.0.1

- Prevent babel transpilation of `typeof` into helper for faster runtime

## 1.0.0

- Initial release

```

```


# fast-equals

Perform [blazing fast](#benchmarks) equality comparisons (either deep or shallow) on two objects passed, while also maintaining a high degree of flexibility for various implementation use-cases. It has no dependencies, and is ~1.8kB when minified and gzipped.

The following types are handled out-of-the-box:

- Plain objects (including `react` elements and `Arguments`)
- Arrays
- Typed Arrays
- `Date` objects
- `RegExp` objects
- `Map` / `Set` iterables
- `Promise` objects
- Primitive wrappers (`new Boolean()` / `new Number()` / `new String()`)
- Custom class instances, including subclasses of native classes

Methods are available for deep, shallow, or referential equality comparison. In addition, you can opt into support for circular objects, or performing a "strict" comparison with unconventional property definition, or both. You can also customize any specific type comparison based on your application's use-cases.

## Table of contents

- [fast-equals](#fast-equals)
  - [Table of contents](#table-of-contents)
  - [Usage](#usage)
    - [Specific builds](#specific-builds)
  - [Available methods](#available-methods)
    - [deepEqual](#deepequal)
      - [Comparing `Map`s](#comparing-maps)
    - [shallowEqual](#shallowequal)
    - [sameValueZeroEqual](#samevaluezeroequal)
    - [circularDeepEqual](#circulardeepequal)
    - [circularShallowEqual](#circularshallowequal)
    - [strictDeepEqual](#strictdeepequal)
    - [strictShallowEqual](#strictshallowequal)
    - [strictCircularDeepEqual](#strictcirculardeepequal)
    - [strictCircularShallowEqual](#strictcircularshallowequal)
    - [createCustomEqual](#createcustomequal)
      - [Recipes](#recipes)
  - [Benchmarks](#benchmarks)
  - [Development](#development)

## Usage

```ts
import { deepEqual } from 'fast-equals';

console.log(deepEqual({ foo: 'bar' }, { foo: 'bar' })); // true
```

### Specific builds

By default, npm should resolve the correct build of the package based on your consumption (ESM vs CommonJS). However, if you want to force use of a specific build, they can be located here:

- ESM => `fast-equals/dist/esm/index.mjs`
- CommonJS => `fast-equals/dist/cjs/index.cjs`
- UMD => `fast-equals/dist/umd/index.js`
- Minified UMD => `fast-equals/dist/min/index.js`

If you are having issues loading a specific build type, [please file an issue](https://github.com/planttheidea/fast-equals/issues).

## Available methods

### deepEqual

Performs a deep equality comparison on the two objects passed and returns a boolean representing the value equivalency of the objects.

```ts
import { deepEqual } from 'fast-equals';

const objectA = { foo: { bar: 'baz' } };
const objectB = { foo: { bar: 'baz' } };

console.log(objectA === objectB); // false
console.log(deepEqual(objectA, objectB)); // true
```

#### Comparing `Map`s

`Map` objects support complex keys (objects, Arrays, etc.), however [the spec for key lookups in `Map` are based on `SameZeroValue`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#key_equality). If the spec were followed for comparison, the following would always be `false`:

```ts
const mapA = new Map([[{ foo: 'bar' }, { baz: 'quz' }]]);
const mapB = new Map([[{ foo: 'bar' }, { baz: 'quz' }]]);

deepEqual(mapA, mapB);
```

To support true deep equality of all contents, `fast-equals` will perform a deep equality comparison for key and value parirs. Therefore, the above would be `true`.

### shallowEqual

Performs a shallow equality comparison on the two objects passed and returns a boolean representing the value equivalency of the objects.

```ts
import { shallowEqual } from 'fast-equals';

const nestedObject = { bar: 'baz' };

const objectA = { foo: nestedObject };
const objectB = { foo: nestedObject };
const objectC = { foo: { bar: 'baz' } };

console.log(objectA === objectB); // false
console.log(shallowEqual(objectA, objectB)); // true
console.log(shallowEqual(objectA, objectC)); // false
```

### sameValueZeroEqual

Performs a [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) comparison on the two objects passed and returns a boolean representing the value equivalency of the objects. In simple terms, this means either strictly equal or both `NaN`.

```ts
import { sameValueZeroEqual } from 'fast-equals';

const mainObject = { foo: NaN, bar: 'baz' };

const objectA = 'baz';
const objectB = NaN;
const objectC = { foo: NaN, bar: 'baz' };

console.log(sameValueZeroEqual(mainObject.bar, objectA)); // true
console.log(sameValueZeroEqual(mainObject.foo, objectB)); // true
console.log(sameValueZeroEqual(mainObject, objectC)); // false
```

### circularDeepEqual

Performs the same comparison as `deepEqual` but supports circular objects. It is slower than `deepEqual`, so only use if you know circular objects are present.

```ts
function Circular(value) {
  this.me = {
    deeply: {
      nested: {
        reference: this,
      },
    },
    value,
  };
}

console.log(circularDeepEqual(new Circular('foo'), new Circular('foo'))); // true
console.log(circularDeepEqual(new Circular('foo'), new Circular('bar'))); // false
```

Just as with `deepEqual`, [both keys and values are compared for deep equality](#comparing-maps).

### circularShallowEqual

Performs the same comparison as `shallowequal` but supports circular objects. It is slower than `shallowEqual`, so only use if you know circular objects are present.

```ts
const array = ['foo'];

array.push(array);

console.log(circularShallowEqual(array, ['foo', array])); // true
console.log(circularShallowEqual(array, [array])); // false
```

### strictDeepEqual

Performs the same comparison as `deepEqual` but performs a strict comparison of the objects. In this includes:

- Checking symbol properties
- Checking non-enumerable properties in object comparisons
- Checking full descriptor of properties on the object to match
- Checking non-index properties on arrays
- Checking non-key properties on `Map` / `Set` objects

```ts
const array = [{ foo: 'bar' }];
const otherArray = [{ foo: 'bar' }];

array.bar = 'baz';
otherArray.bar = 'baz';

console.log(strictDeepEqual(array, otherArray)); // true;
console.log(strictDeepEqual(array, [{ foo: 'bar' }])); // false;
```

### strictShallowEqual

Performs the same comparison as `shallowEqual` but performs a strict comparison of the objects. In this includes:

- Checking non-enumerable properties in object comparisons
- Checking full descriptor of properties on the object to match
- Checking non-index properties on arrays
- Checking non-key properties on `Map` / `Set` objects

```ts
const array = ['foo'];
const otherArray = ['foo'];

array.bar = 'baz';
otherArray.bar = 'baz';

console.log(strictDeepEqual(array, otherArray)); // true;
console.log(strictDeepEqual(array, ['foo'])); // false;
```

### strictCircularDeepEqual

Performs the same comparison as `circularDeepEqual` but performs a strict comparison of the objects. In this includes:

- Checking `Symbol` properties on the object
- Checking non-enumerable properties in object comparisons
- Checking full descriptor of properties on the object to match
- Checking non-index properties on arrays
- Checking non-key properties on `Map` / `Set` objects

```ts
function Circular(value) {
  this.me = {
    deeply: {
      nested: {
        reference: this,
      },
    },
    value,
  };
}

const first = new Circular('foo');

Object.defineProperty(first, 'bar', {
  enumerable: false,
  value: 'baz',
});

const second = new Circular('foo');

Object.defineProperty(second, 'bar', {
  enumerable: false,
  value: 'baz',
});

console.log(circularDeepEqual(first, second)); // true
console.log(circularDeepEqual(first, new Circular('foo'))); // false
```

### strictCircularShallowEqual

Performs the same comparison as `circularShallowEqual` but performs a strict comparison of the objects. In this includes:

- Checking non-enumerable properties in object comparisons
- Checking full descriptor of properties on the object to match
- Checking non-index properties on arrays
- Checking non-key properties on `Map` / `Set` objects

```ts
const array = ['foo'];
const otherArray = ['foo'];

array.push(array);
otherArray.push(otherArray);

array.bar = 'baz';
otherArray.bar = 'baz';

console.log(circularShallowEqual(array, otherArray)); // true
console.log(circularShallowEqual(array, ['foo', array])); // false
```

### createCustomEqual

Creates a custom equality comparator that will be used on nested values in the object. Unlike `deepEqual` and `shallowEqual`, this is a factory method that receives the default options used internally, and allows you to override the defaults as needed. This is generally for extreme edge-cases, or supporting legacy environments.

The signature is as follows:

```ts
interface Cache<Key extends object, Value> {
  delete(key: Key): boolean;
  get(key: Key): Value | undefined;
  set(key: Key, value: any): any;
}

interface ComparatorConfig<Meta> {
  areArraysEqual: TypeEqualityComparator<any[], Meta>;
  areDatesEqual: TypeEqualityComparator<Date, Meta>;
  areMapsEqual: TypeEqualityComparator<Map<any, any>, Meta>;
  areObjectsEqual: TypeEqualityComparator<Record<string, any>, Meta>;
  arePrimitiveWrappersEqual: TypeEqualityComparator<
    boolean | string | number,
    Meta
  >;
  areRegExpsEqual: TypeEqualityComparator<RegExp, Meta>;
  areSetsEqual: TypeEqualityComparator<Set<any>, Meta>;
  areTypedArraysEqual: TypeEqualityComparatory<TypedArray, Meta>;
}

function createCustomEqual<Meta>(options: {
  circular?: boolean;
  createCustomConfig?: (
    defaultConfig: ComparatorConfig<Meta>,
  ) => Partial<ComparatorConfig<Meta>>;
  createInternalComparator?: (
    compare: <A, B>(a: A, b: B, state: State<Meta>) => boolean,
  ) => (
    a: any,
    b: any,
    indexOrKeyA: any,
    indexOrKeyB: any,
    parentA: any,
    parentB: any,
    state: State<Meta>,
  ) => boolean;
  createState?: () => { cache?: Cache; meta?: Meta };
  strict?: boolean;
}): <A, B>(a: A, b: B) => boolean;
```

Create a custom equality comparator. This allows complete control over building a bespoke equality method, in case your use-case requires a higher degree of performance, legacy environment support, or any other non-standard usage. The [recipes](#recipes) provide examples of use in different use-cases, but if you have a specific goal in mind and would like assistance feel free to [file an issue](https://github.com/planttheidea/fast-equals/issues).

_**NOTE**: `Map` implementations compare equality for both keys and value. When using a custom comparator and comparing equality of the keys, the iteration index is provided as both `indexOrKeyA` and `indexOrKeyB` to help use-cases where ordering of keys matters to equality._

#### Recipes

Some recipes have been created to provide examples of use-cases for `createCustomEqual`. Even if not directly applicable to the problem you are solving, they can offer guidance of how to structure your solution.

- [Legacy environment support for `RegExp` comparators](./recipes/legacy-regexp-support.md)
- [Explicit property check](./recipes/explicit-property-check.md)
- [Using `meta` in comparison](./recipes//using-meta-in-comparison.md)
- [Comparing non-standard properties](./recipes/non-standard-properties.md)
- [Strict property descriptor comparison](./recipes/strict-property-descriptor-check.md)
- [Legacy environment support for circualr equal comparators](./recipes/legacy-circular-equal-support.md)

## Benchmarks

All benchmarks were performed on an i9-11900H Ubuntu Linux 22.04 laptop with 64GB of memory using NodeJS version `16.14.2`, and are based on averages of running comparisons based deep equality on the following object types:

- Primitives (`String`, `Number`, `null`, `undefined`)
- `Function`
- `Object`
- `Array`
- `Date`
- `RegExp`
- `react` elements
- A mixed object with a combination of all the above types

```bash
Testing mixed objects equal...
┌─────────┬─────────────────────────────────┬────────────────┐
│ (index) │             Package             │    Ops/sec     │
├─────────┼─────────────────────────────────┼────────────────┤
│    0    │          'fast-equals'          │ 1249567.730326 │
│    1    │        'fast-deep-equal'        │ 1182463.587514 │
│    2    │      'react-fast-compare'       │ 1152487.319161 │
│    3    │      'shallow-equal-fuzzy'      │ 1092360.712389 │
│    4    │    'fast-equals (circular)'     │  676669.92003  │
│    5    │      'underscore.isEqual'       │ 429430.837497  │
│    6    │        'lodash.isEqual'         │ 237915.684734  │
│    7    │     'fast-equals (strict)'      │  181386.38032  │
│    8    │ 'fast-equals (strict circular)' │ 156779.745875  │
│    9    │           'deep-eql'            │ 139155.099209  │
│   10    │          'deep-equal'           │  1026.527229   │
└─────────┴─────────────────────────────────┴────────────────┘

Testing mixed objects not equal...
┌─────────┬─────────────────────────────────┬────────────────┐
│ (index) │             Package             │    Ops/sec     │
├─────────┼─────────────────────────────────┼────────────────┤
│    0    │          'fast-equals'          │ 3255824.097237 │
│    1    │      'react-fast-compare'       │ 2654721.726058 │
│    2    │        'fast-deep-equal'        │ 2582218.974752 │
│    3    │    'fast-equals (circular)'     │ 2474303.26566  │
│    4    │     'fast-equals (strict)'      │ 1088066.604881 │
│    5    │ 'fast-equals (strict circular)' │ 949253.614181  │
│    6    │          'nano-equal'           │ 939170.554148  │
│    7    │      'underscore.isEqual'       │ 738852.197879  │
│    8    │        'lodash.isEqual'         │ 307306.622212  │
│    9    │           'deep-eql'            │ 156250.110401  │
│   10    │    'assert.deepStrictEqual'     │  22839.454561  │
│   11    │          'deep-equal'           │   4034.45114   │
└─────────┴─────────────────────────────────┴────────────────┘
```

Caveats that impact the benchmark (and accuracy of comparison):

- `Map`s, `Promise`s, and `Set`s were excluded from the benchmark entirely because no library other than `deep-eql` fully supported their comparison
- `fast-deep-equal`, `react-fast-compare` and `nano-equal` throw on objects with `null` as prototype (`Object.create(null)`)
- `assert.deepStrictEqual` does not support `NaN` or `SameValueZero` equality for dates
- `deep-eql` does not support `SameValueZero` equality for zero equality (positive and negative zero are not equal)
- `deep-equal` does not support `NaN` and does not strictly compare object type, or date / regexp values, nor uses `SameValueZero` equality for dates
- `fast-deep-equal` does not support `NaN` or `SameValueZero` equality for dates
- `nano-equal` does not strictly compare object property structure, array length, or object type, nor `SameValueZero` equality for dates
- `react-fast-compare` does not support `NaN` or `SameValueZero` equality for dates, and does not compare `function` equality
- `shallow-equal-fuzzy` does not strictly compare object type or regexp values, nor `SameValueZero` equality for dates
- `underscore.isEqual` does not support `SameValueZero` equality for primitives or dates

All of these have the potential of inflating the respective library's numbers in comparison to `fast-equals`, but it was the closest apples-to-apples comparison I could create of a reasonable sample size. It should be noted that `react` elements can be circular objects, however simple elements are not; I kept the `react` comparison very basic to allow it to be included.

## Development

Standard practice, clone the repo and `npm i` to get the dependencies. The following npm scripts are available:

- benchmark => run benchmark tests against other equality libraries
- build => build `main`, `module`, and `browser` distributables with `rollup`
- clean => run `rimraf` on the `dist` folder
- dev => start webpack playground App
- dist => run `build`
- lint => run ESLint on all files in `src` folder (also runs on `dev` script)
- lint:fix => run `lint` script, but with auto-fixer
- prepublish:compile => run `lint`, `test:coverage`, `transpile:lib`, `transpile:es`, and `dist` scripts
- start => run `dev`
- test => run AVA with NODE_ENV=test on all files in `test` folder
- test:coverage => run same script as `test` with code coverage calculation via `nyc`
- test:watch => run same script as `test` but keep persistent watcher


# fast-glob

> It's a very fast and efficient [glob][glob_definition] library for [Node.js][node_js].

This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in **arbitrary order**. Quick, simple, effective.

## Table of Contents

Details

* [Highlights](#highlights)
* [Old and modern mode](#old-and-modern-mode)
* [Pattern syntax](#pattern-syntax)
  * [Basic syntax](#basic-syntax)
  * [Advanced syntax](#advanced-syntax)
* [Installation](#installation)
* [API](#api)
  * [Asynchronous](#asynchronous)
  * [Synchronous](#synchronous)
  * [Stream](#stream)
    * [patterns](#patterns)
    * [[options]](#options)
  * [Helpers](#helpers)
    * [generateTasks](#generatetaskspatterns-options)
    * [isDynamicPattern](#isdynamicpatternpattern-options)
    * [escapePath](#escapepathpath)
	* [convertPathToPattern](#convertpathtopatternpath)
* [Options](#options-3)
  * [Common](#common)
    * [concurrency](#concurrency)
    * [cwd](#cwd)
    * [deep](#deep)
    * [followSymbolicLinks](#followsymboliclinks)
    * [fs](#fs)
    * [ignore](#ignore)
    * [suppressErrors](#suppresserrors)
    * [throwErrorOnBrokenSymbolicLink](#throwerroronbrokensymboliclink)
  * [Output control](#output-control)
    * [absolute](#absolute)
    * [markDirectories](#markdirectories)
    * [objectMode](#objectmode)
    * [onlyDirectories](#onlydirectories)
    * [onlyFiles](#onlyfiles)
    * [stats](#stats)
    * [unique](#unique)
  * [Matching control](#matching-control)
    * [braceExpansion](#braceexpansion)
    * [caseSensitiveMatch](#casesensitivematch)
    * [dot](#dot)
    * [extglob](#extglob)
    * [globstar](#globstar)
    * [baseNameMatch](#basenamematch)
* [FAQ](#faq)
  * [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern)
  * [How to write patterns on Windows?](#how-to-write-patterns-on-windows)
  * [Why are parentheses match wrong?](#why-are-parentheses-match-wrong)
  * [How to exclude directory from reading?](#how-to-exclude-directory-from-reading)
  * [How to use UNC path?](#how-to-use-unc-path)
  * [Compatible with `node-glob`?](#compatible-with-node-glob)
* [Benchmarks](#benchmarks)
  * [Server](#server)
  * [Nettop](#nettop)
* [Changelog](#changelog)
* [License](#license)

## Highlights

* Fast. Probably the fastest.
* Supports multiple and negative patterns.
* Synchronous, Promise and Stream API.
* Object mode. Can return more than just strings.
* Error-tolerant.

## Old and modern mode

This package works in two modes, depending on the environment in which it is used.

* **Old mode**. Node.js below 10.10 or when the [`stats`](#stats) option is *enabled*.
* **Modern mode**. Node.js 10.10+ and the [`stats`](#stats) option is *disabled*.

The modern mode is faster. Learn more about the [internal mechanism][nodelib_fs_scandir_old_and_modern_modern].

## Pattern syntax

> :warning: Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters.

There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our [FAQ](#faq).

> :book: This package uses [`micromatch`][micromatch] as a library for pattern matching.

### Basic syntax

* An asterisk (`*`) — matches everything except slashes (path separators), hidden files (names starting with `.`).
* A double star or globstar (`**`) — matches zero or more directories.
* Question mark (`?`) – matches any single character except slashes (path separators).
* Sequence (`[seq]`) — matches any character in sequence.

> :book: A few additional words about the [basic matching behavior][picomatch_matching_behavior].

Some examples:

* `src/**/*.js` — matches all files in the `src` directory (any level of nesting) that have the `.js` extension.
* `src/*.??` — matches all files in the `src` directory (only first level of nesting) that have a two-character extension.
* `file-[01].js` — matches files: `file-0.js`, `file-1.js`.

### Advanced syntax

* [Escapes characters][micromatch_backslashes] (`\\`) — matching special characters (`$^*+?()[]`) as literals.
* [POSIX character classes][picomatch_posix_brackets] (`[[:digit:]]`).
* [Extended globs][micromatch_extglobs] (`?(pattern-list)`).
* [Bash style brace expansions][micromatch_braces] (`{}`).
* [Regexp character classes][micromatch_regex_character_classes] (`[1-5]`).
* [Regex groups][regular_expressions_brackets] (`(a|b)`).

> :book: A few additional words about the [advanced matching behavior][micromatch_extended_globbing].

Some examples:

* `src/**/*.{css,scss}` — matches all files in the `src` directory (any level of nesting) that have the `.css` or `.scss` extension.
* `file-[[:digit:]].js` — matches files: `file-0.js`, `file-1.js`, …, `file-9.js`.
* `file-{1..3}.js` — matches files: `file-1.js`, `file-2.js`, `file-3.js`.
* `file-(1|2)` — matches files: `file-1.js`, `file-2.js`.

## Installation

```console
npm install fast-glob
```

## API

### Asynchronous

```js
fg(patterns, [options])
fg.async(patterns, [options])
fg.glob(patterns, [options])
```

Returns a `Promise` with an array of matching entries.

```js
const fg = require('fast-glob');

const entries = await fg(['.editorconfig', '**/index.js'], { dot: true });

// ['.editorconfig', 'services/index.js']
```

### Synchronous

```js
fg.sync(patterns, [options])
fg.globSync(patterns, [options])
```

Returns an array of matching entries.

```js
const fg = require('fast-glob');

const entries = fg.sync(['.editorconfig', '**/index.js'], { dot: true });

// ['.editorconfig', 'services/index.js']
```

### Stream

```js
fg.stream(patterns, [options])
fg.globStream(patterns, [options])
```

Returns a [`ReadableStream`][node_js_stream_readable_streams] when the `data` event will be emitted with matching entry.

```js
const fg = require('fast-glob');

const stream = fg.stream(['.editorconfig', '**/index.js'], { dot: true });

for await (const entry of stream) {
	// .editorconfig
	// services/index.js
}
```

#### patterns

* Required: `true`
* Type: `string | string[]`

Any correct pattern(s).

> :1234: [Pattern syntax](#pattern-syntax)
>
> :warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls.

#### [options]

* Required: `false`
* Type: [`Options`](#options-3)

See [Options](#options-3) section.

### Helpers

#### `generateTasks(patterns, [options])`

Returns the internal representation of patterns ([`Task`](./src/managers/tasks.ts) is a combining patterns by base directory).

```js
fg.generateTasks('*');

[{
    base: '.', // Parent directory for all patterns inside this task
    dynamic: true, // Dynamic or static patterns are in this task
    patterns: ['*'],
    positive: ['*'],
    negative: []
}]
```

##### patterns

* Required: `true`
* Type: `string | string[]`

Any correct pattern(s).

##### [options]

* Required: `false`
* Type: [`Options`](#options-3)

See [Options](#options-3) section.

#### `isDynamicPattern(pattern, [options])`

Returns `true` if the passed pattern is a dynamic pattern.

> :1234: [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern)

```js
fg.isDynamicPattern('*'); // true
fg.isDynamicPattern('abc'); // false
```

##### pattern

* Required: `true`
* Type: `string`

Any correct pattern.

##### [options]

* Required: `false`
* Type: [`Options`](#options-3)

See [Options](#options-3) section.

#### `escapePath(path)`

Returns the path with escaped special characters depending on the platform.

* Posix:
  * `*?|(){}[]`;
  * `!` at the beginning of line;
  * `@+!` before the opening parenthesis;
  * `\\` before non-special characters;
* Windows:
  * `(){}[]`
  * `!` at the beginning of line;
  * `@+!` before the opening parenthesis;
  * Characters like `*?|` cannot be used in the path ([windows_naming_conventions][windows_naming_conventions]), so they will not be escaped;

```js
fg.escapePath('!abc');
// \\!abc
fg.escapePath('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac'
// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac

fg.posix.escapePath('C:\\Program Files (x86)\\**\\*');
// C:\\\\Program Files \\(x86\\)\\*\\*\\*
fg.win32.escapePath('C:\\Program Files (x86)\\**\\*');
// Windows: C:\\Program Files \\(x86\\)\\**\\*
```

#### `convertPathToPattern(path)`

Converts a path to a pattern depending on the platform, including special character escaping.

* Posix. Works similarly to the `fg.posix.escapePath` method.
* Windows. Works similarly to the `fg.win32.escapePath` method, additionally converting backslashes to forward slashes in cases where they are not escape characters (`!()+@{}[]`).

```js
fg.convertPathToPattern('[OpenSource] mrmlnc – fast-glob (Deluxe Edition) 2014') + '/*.flac';
// \\[OpenSource\\] mrmlnc – fast-glob \\(Deluxe Edition\\) 2014/*.flac

fg.convertPathToPattern('C:/Program Files (x86)/**/*');
// Posix: C:/Program Files \\(x86\\)/\\*\\*/\\*
// Windows: C:/Program Files \\(x86\\)/**/*

fg.convertPathToPattern('C:\\Program Files (x86)\\**\\*');
// Posix: C:\\\\Program Files \\(x86\\)\\*\\*\\*
// Windows: C:/Program Files \\(x86\\)/**/*

fg.posix.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*';
// Posix: \\\\\\?\\\\c:\\\\Program Files \\(x86\\)/**/* (broken pattern)
fg.win32.convertPathToPattern('\\\\?\\c:\\Program Files (x86)') + '/**/*';
// Windows: //?/c:/Program Files \\(x86\\)/**/*
```

## Options

### Common options

#### concurrency

* Type: `number`
* Default: `os.cpus().length`

Specifies the maximum number of concurrent requests from a reader to read directories.

> :book: The higher the number, the higher the performance and load on the file system. If you want to read in quiet mode, set the value to a comfortable number or `1`.

More details

In Node, there are [two types of threads][nodejs_thread_pool]: Event Loop (code) and a Thread Pool (fs, dns, …). The thread pool size controlled by the `UV_THREADPOOL_SIZE` environment variable. Its default size is 4 ([documentation][libuv_thread_pool]). The pool is one for all tasks within a single Node process.

Any code can make 4 real concurrent accesses to the file system. The rest of the FS requests will wait in the queue.

> :book: Each new instance of FG in the same Node process will use the same Thread pool.

But this package also has the `concurrency` option. This option allows you to control the number of concurrent accesses to the FS at the package level. By default, this package has a value equal to the number of cores available for the current Node process. This allows you to set a value smaller than the pool size (`concurrency: 1`) or, conversely, to prepare tasks for the pool queue more quickly (`concurrency: Number.POSITIVE_INFINITY`).

So, in fact, this package can **only make 4 concurrent requests to the FS**. You can increase this value by using an environment variable (`UV_THREADPOOL_SIZE`), but in practice this does not give a multiple advantage.

#### cwd

* Type: `string`
* Default: `process.cwd()`

The current working directory in which to search.

#### deep

* Type: `number`
* Default: `Infinity`

Specifies the maximum depth of a read directory relative to the start directory.

For example, you have the following tree:

```js
dir/
└── one/            // 1
    └── two/        // 2
        └── file.js // 3
```

```js
// With base directory
fg.sync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one']
fg.sync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two']

// With cwd option
fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one']
fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two']
```

> :book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a [`cwd`](#cwd) option.

#### followSymbolicLinks

* Type: `boolean`
* Default: `true`

Indicates whether to traverse descendants of symbolic link directories when expanding `**` patterns.

> :book: Note that this option does not affect the base directory of the pattern. For example, if `./a` is a symlink to directory `./b` and you specified `['./a**', './b/**']` patterns, then directory `./a` will still be read.

> :book: If the [`stats`](#stats) option is specified, the information about the symbolic link (`fs.lstat`) will be replaced with information about the entry (`fs.stat`) behind it.

#### fs

* Type: `FileSystemAdapter`
* Default: `fs.*`

Custom implementation of methods for working with the file system.

```ts
export interface FileSystemAdapter {
    lstat?: typeof fs.lstat;
    stat?: typeof fs.stat;
    lstatSync?: typeof fs.lstatSync;
    statSync?: typeof fs.statSync;
    readdir?: typeof fs.readdir;
    readdirSync?: typeof fs.readdirSync;
}
```

#### ignore

* Type: `string[]`
* Default: `[]`

An array of glob patterns to exclude matches. This is an alternative way to use negative patterns.

```js
dir/
├── package-lock.json
└── package.json
```

```js
fg.sync(['*.json', '!package-lock.json']);            // ['package.json']
fg.sync('*.json', { ignore: ['package-lock.json'] }); // ['package.json']
```

#### suppressErrors

* Type: `boolean`
* Default: `false`

By default this package suppress only `ENOENT` errors. Set to `true` to suppress any error.

> :book: Can be useful when the directory has entries with a special level of access.

#### throwErrorOnBrokenSymbolicLink

* Type: `boolean`
* Default: `false`

Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`.

> :book: This option has no effect on errors when reading the symbolic link directory.

### Output control

#### absolute

* Type: `boolean`
* Default: `false`

Return the absolute path for entries.

```js
fg.sync('*.js', { absolute: false }); // ['index.js']
fg.sync('*.js', { absolute: true });  // ['/home/user/index.js']
```

> :book: This option is required if you want to use negative patterns with absolute path, for example, `!${__dirname}/*.js`.

#### markDirectories

* Type: `boolean`
* Default: `false`

Mark the directory path with the final slash.

```js
fg.sync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers']
fg.sync('*', { onlyFiles: false, markDirectories: true });  // ['index.js', 'controllers/']
```

#### objectMode

* Type: `boolean`
* Default: `false`

Returns objects (instead of strings) describing entries.

```js
fg.sync('*', { objectMode: false }); // ['src/index.js']
fg.sync('*', { objectMode: true });  // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent> }]
```

The object has the following fields:

* name (`string`) — the last part of the path (basename)
* path (`string`) — full path relative to the pattern base directory
* dirent ([`fs.Dirent`][node_js_fs_class_fs_dirent]) — instance of `fs.Dirent`

> :book: An object is an internal representation of entry, so getting it does not affect performance.

#### onlyDirectories

* Type: `boolean`
* Default: `false`

Return only directories.

```js
fg.sync('*', { onlyDirectories: false }); // ['index.js', 'src']
fg.sync('*', { onlyDirectories: true });  // ['src']
```

> :book: If `true`, the [`onlyFiles`](#onlyfiles) option is automatically `false`.

#### onlyFiles

* Type: `boolean`
* Default: `true`

Return only files.

```js
fg.sync('*', { onlyFiles: false }); // ['index.js', 'src']
fg.sync('*', { onlyFiles: true });  // ['index.js']
```

#### stats

* Type: `boolean`
* Default: `false`

Enables an [object mode](#objectmode) with an additional field:

* stats ([`fs.Stats`][node_js_fs_class_fs_stats]) — instance of `fs.Stats`

```js
fg.sync('*', { stats: false }); // ['src/index.js']
fg.sync('*', { stats: true });  // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent>, stats: <fs.Stats> }]
```

> :book: Returns `fs.stat` instead of `fs.lstat` for symbolic links when the [`followSymbolicLinks`](#followsymboliclinks) option is specified.
>
> :warning: Unlike [object mode](#objectmode) this mode requires additional calls to the file system. On average, this mode is slower at least twice. See [old and modern mode](#old-and-modern-mode) for more details.

#### unique

* Type: `boolean`
* Default: `true`

Ensures that the returned entries are unique.

```js
fg.sync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json']
fg.sync(['*.json', 'package.json'], { unique: true });  // ['package.json']
```

If `true` and similar entries are found, the result is the first found.

### Matching control

#### braceExpansion

* Type: `boolean`
* Default: `true`

Enables Bash-like brace expansion.

> :1234: [Syntax description][bash_hackers_syntax_expansion_brace] or more [detailed description][micromatch_braces].

```js
dir/
├── abd
├── acd
└── a{b,c}d
```

```js
fg.sync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d']
fg.sync('a{b,c}d', { braceExpansion: true });  // ['abd', 'acd']
```

#### caseSensitiveMatch

* Type: `boolean`
* Default: `true`

Enables a [case-sensitive][wikipedia_case_sensitivity] mode for matching files.

```js
dir/
├── file.txt
└── File.txt
```

```js
fg.sync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt']
fg.sync('file.txt', { caseSensitiveMatch: true });  // ['file.txt']
```

#### dot

* Type: `boolean`
* Default: `false`

Allow patterns to match entries that begin with a period (`.`).

> :book: Note that an explicit dot in a portion of the pattern will always match dot files.

```js
dir/
├── .editorconfig
└── package.json
```

```js
fg.sync('*', { dot: false }); // ['package.json']
fg.sync('*', { dot: true });  // ['.editorconfig', 'package.json']
```

#### extglob

* Type: `boolean`
* Default: `true`

Enables Bash-like `extglob` functionality.

> :1234: [Syntax description][micromatch_extglobs].

```js
dir/
├── README.md
└── package.json
```

```js
fg.sync('*.+(json|md)', { extglob: false }); // []
fg.sync('*.+(json|md)', { extglob: true });  // ['README.md', 'package.json']
```

#### globstar

* Type: `boolean`
* Default: `true`

Enables recursively repeats a pattern containing `**`. If `false`, `**` behaves exactly like `*`.

```js
dir/
└── a
    └── b
```

```js
fg.sync('**', { onlyFiles: false, globstar: false }); // ['a']
fg.sync('**', { onlyFiles: false, globstar: true });  // ['a', 'a/b']
```

#### baseNameMatch

* Type: `boolean`
* Default: `false`

If set to `true`, then patterns without slashes will be matched against the basename of the path if it contains slashes.

```js
dir/
└── one/
    └── file.md
```

```js
fg.sync('*.md', { baseNameMatch: false }); // []
fg.sync('*.md', { baseNameMatch: true });  // ['one/file.md']
```

## FAQ

## What is a static or dynamic pattern?

All patterns can be divided into two types:

* **static**. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the `file.js` pattern is a static pattern because we can just verify that it exists on the file system.
* **dynamic**. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the `*` pattern is a dynamic pattern because we cannot use this pattern directly.

A pattern is considered dynamic if it contains the following characters (`…` — any characters or their absence) or options:

* The [`caseSensitiveMatch`](#casesensitivematch) option is disabled
* `\\` (the escape character)
* `*`, `?`, `!` (at the beginning of line)
* `[…]`
* `(…|…)`
* `@(…)`, `!(…)`, `*(…)`, `?(…)`, `+(…)` (respects the [`extglob`](#extglob) option)
* `{…,…}`, `{…..…}` (respects the [`braceExpansion`](#braceexpansion) option)

## How to write patterns on Windows?

Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. With the [`cwd`](#cwd) option use a convenient format.

**Bad**

```ts
[
	'directory\\*',
	path.join(process.cwd(), '**')
]
```

**Good**

```ts
[
	'directory/*',
	fg.convertPathToPattern(process.cwd()) + '/**'
]
```

> :book: Use the [`.convertPathToPattern`](#convertpathtopatternpath) package to convert Windows-style path to a Unix-style path.

Read more about [matching with backslashes][micromatch_backslashes].

## Why are parentheses match wrong?

```js
dir/
└── (special-*file).txt
```

```js
fg.sync(['(special-*file).txt']) // []
```

Refers to Bash. You need to escape special characters:

```js
fg.sync(['\\(special-*file\\).txt']) // ['(special-*file).txt']
```

Read more about [matching special characters as literals][picomatch_matching_special_characters_as_literals]. Or use the [`.escapePath`](#escapepathpath).

## How to exclude directory from reading?

You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use [`ignore`](#ignore) option. Just look at the example below.

```js
first/
├── file.md
└── second/
    └── file.txt
```

If you don't want to read the `second` directory, you must write the following pattern: `!**/second` or `!**/second/**`.

```js
fg.sync(['**/*.md', '!**/second']);                 // ['first/file.md']
fg.sync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md']
```

> :warning: When you write `!**/second/**/*` it means that the directory will be **read**, but all the entries will not be included in the results.

You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances.

## How to use UNC path?

You cannot use [Uniform Naming Convention (UNC)][unc_path] paths as patterns (due to syntax) directly, but you can use them as [`cwd`](#cwd) directory or use the `fg.convertPathToPattern` method.

```ts
// cwd
fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ });
fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ });

// .convertPathToPattern
fg.sync(fg.convertPathToPattern('\\\\?\\c:\\Python27') + '/*');
```

## Compatible with `node-glob`?

| node-glob    | fast-glob |
| :----------: | :-------: |
| `cwd`        | [`cwd`](#cwd) |
| `root`       | – |
| `dot`        | [`dot`](#dot) |
| `nomount`    | – |
| `mark`       | [`markDirectories`](#markdirectories) |
| `nosort`     | – |
| `nounique`   | [`unique`](#unique) |
| `nobrace`    | [`braceExpansion`](#braceexpansion) |
| `noglobstar` | [`globstar`](#globstar) |
| `noext`      | [`extglob`](#extglob) |
| `nocase`     | [`caseSensitiveMatch`](#casesensitivematch) |
| `matchBase`  | [`baseNameMatch`](#basenamematch) |
| `nodir`      | [`onlyFiles`](#onlyfiles) |
| `ignore`     | [`ignore`](#ignore) |
| `follow`     | [`followSymbolicLinks`](#followsymboliclinks) |
| `realpath`   | – |
| `absolute`   | [`absolute`](#absolute) |

## Benchmarks

You can see results [here](https://github.com/mrmlnc/fast-glob/actions/workflows/benchmark.yml?query=branch%3Amaster) for every commit into the `main` branch.

* **Product benchmark** – comparison with the main competitors.
* **Regress benchmark** – regression between the current version and the version from the npm registry.

## Changelog

See the [Releases section of our GitHub project][github_releases] for changelog for each release version.

## License

This software is released under the terms of the MIT license.

[bash_hackers_syntax_expansion_brace]: https://wiki.bash-hackers.org/syntax/expansion/brace
[github_releases]: https://github.com/mrmlnc/fast-glob/releases
[glob_definition]: https://en.wikipedia.org/wiki/Glob_(programming)
[glob_linux_man]: http://man7.org/linux/man-pages/man3/glob.3.html
[micromatch_backslashes]: https://github.com/micromatch/micromatch#backslashes
[micromatch_braces]: https://github.com/micromatch/braces
[micromatch_extended_globbing]: https://github.com/micromatch/micromatch#extended-globbing
[micromatch_extglobs]: https://github.com/micromatch/micromatch#extglobs
[micromatch_regex_character_classes]: https://github.com/micromatch/micromatch#regex-character-classes
[micromatch]: https://github.com/micromatch/micromatch
[node_js_fs_class_fs_dirent]: https://nodejs.org/api/fs.html#fs_class_fs_dirent
[node_js_fs_class_fs_stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats
[node_js_stream_readable_streams]: https://nodejs.org/api/stream.html#stream_readable_streams
[node_js]: https://nodejs.org/en
[nodelib_fs_scandir_old_and_modern_modern]: https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode
[npm_normalize_path]: https://www.npmjs.com/package/normalize-path
[npm_unixify]: https://www.npmjs.com/package/unixify
[picomatch_matching_behavior]: https://github.com/micromatch/picomatch#matching-behavior-vs-bash
[picomatch_matching_special_characters_as_literals]: https://github.com/micromatch/picomatch#matching-special-characters-as-literals
[picomatch_posix_brackets]: https://github.com/micromatch/picomatch#posix-brackets
[regular_expressions_brackets]: https://www.regular-expressions.info/brackets.html
[unc_path]: https://learn.microsoft.com/openspecs/windows_protocols/ms-dtyp/62e862f4-2a51-452e-8eeb-dc4ff5ee33cc
[wikipedia_case_sensitivity]: https://en.wikipedia.org/wiki/Case_sensitivity
[nodejs_thread_pool]: https://nodejs.org/en/docs/guides/dont-block-the-event-loop
[libuv_thread_pool]: http://docs.libuv.org/en/v1.x/threadpool.html
[windows_naming_conventions]: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions


# fastq

![ci][ci-url]
[![npm version][npm-badge]][npm-url]

Fast, in memory work queue.

Benchmarks (1 million tasks):

* setImmediate: 812ms
* fastq: 854ms
* async.queue: 1298ms
* neoAsync.queue: 1249ms

Obtained on node 12.16.1, on a dedicated server.

If you need zero-overhead series function call, check out
[fastseries](http://npm.im/fastseries). For zero-overhead parallel
function call, check out [fastparallel](http://npm.im/fastparallel).

[![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard)

  * Installation
  * Usage
  * API
  * Licence & copyright

## Install

`npm i fastq --save`

## Usage (callback API)

```js
'use strict'

const queue = require('fastq')(worker, 1)

queue.push(42, function (err, result) {
  if (err) { throw err }
  console.log('the result is', result)
})

function worker (arg, cb) {
  cb(null, arg * 2)
}
```

## Usage (promise API)

```js
const queue = require('fastq').promise(worker, 1)

async function worker (arg) {
  return arg * 2
}

async function run () {
  const result = await queue.push(42)
  console.log('the result is', result)
}

run()
```

### Setting "this"

```js
'use strict'

const that = { hello: 'world' }
const queue = require('fastq')(that, worker, 1)

queue.push(42, function (err, result) {
  if (err) { throw err }
  console.log(this)
  console.log('the result is', result)
})

function worker (arg, cb) {
  console.log(this)
  cb(null, arg * 2)
}
```

### Using with TypeScript (callback API)

```ts
'use strict'

import * as fastq from "fastq";
import type { queue, done } from "fastq";

type Task = {
  id: number
}

const q: queue<Task> = fastq(worker, 1)

q.push({ id: 42})

function worker (arg: Task, cb: done) {
  console.log(arg.id)
  cb(null)
}
```

### Using with TypeScript (promise API)

```ts
'use strict'

import * as fastq from "fastq";
import type { queueAsPromised } from "fastq";

type Task = {
  id: number
}

const q: queueAsPromised<Task> = fastq.promise(asyncWorker, 1)

q.push({ id: 42}).catch((err) => console.error(err))

async function asyncWorker (arg: Task): Promise<void> {
  // No need for a try-catch block, fastq handles errors automatically
  console.log(arg.id)
}
```

## API

* fastqueue()
* queue#push()
* queue#unshift()
* queue#pause()
* queue#resume()
* queue#idle()
* queue#length()
* queue#getQueue()
* queue#kill()
* queue#killAndDrain()
* queue#error()
* queue#concurrency
* queue#drain
* queue#empty
* queue#saturated
* fastqueue.promise()

-------------------------------------------------------

### fastqueue([that], worker, concurrency)

Creates a new queue.

Arguments:

* `that`, optional context of the `worker` function.
* `worker`, worker function, it would be called with `that` as `this`,
  if that is specified.
* `concurrency`, number of concurrent tasks that could be executed in
  parallel.

-------------------------------------------------------

### queue.push(task, done)

Add a task at the end of the queue. `done(err, result)` will be called
when the task was processed.

-------------------------------------------------------

### queue.unshift(task, done)

Add a task at the beginning of the queue. `done(err, result)` will be called
when the task was processed.

-------------------------------------------------------

### queue.pause()

Pause the processing of tasks. Currently worked tasks are not
stopped.

-------------------------------------------------------

### queue.resume()

Resume the processing of tasks.

-------------------------------------------------------

### queue.idle()

Returns `false` if there are tasks being processed or waiting to be processed.
`true` otherwise.

-------------------------------------------------------

### queue.length()

Returns the number of tasks waiting to be processed (in the queue).

-------------------------------------------------------

### queue.getQueue()

Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks

-------------------------------------------------------

### queue.kill()

Removes all tasks waiting to be processed, and reset `drain` to an empty
function.

-------------------------------------------------------

### queue.killAndDrain()

Same than `kill` but the `drain` function will be called before reset to empty.

-------------------------------------------------------

### queue.error(handler)

Set a global error handler. `handler(err, task)` will be called
each time a task is completed, `err` will be not null if the task has thrown an error.

-------------------------------------------------------

### queue.concurrency

Property that returns the number of concurrent tasks that could be executed in
parallel. It can be altered at runtime.

-------------------------------------------------------

### queue.drain

Function that will be called when the last
item from the queue has been processed by a worker.
It can be altered at runtime.

-------------------------------------------------------

### queue.empty

Function that will be called when the last
item from the queue has been assigned to a worker.
It can be altered at runtime.

-------------------------------------------------------

### queue.saturated

Function that will be called when the queue hits the concurrency
limit.
It can be altered at runtime.

-------------------------------------------------------

### fastqueue.promise([that], worker(arg), concurrency)

Creates a new queue with `Promise` apis. It also offers all the methods
and properties of the object returned by [`fastqueue`](#fastqueue) with the modified
[`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods.

Node v10+ is required to use the promisified version.

Arguments:
* `that`, optional context of the `worker` function.
* `worker`, worker function, it would be called with `that` as `this`,
  if that is specified. It MUST return a `Promise`.
* `concurrency`, number of concurrent tasks that could be executed in
  parallel.

#### queue.push(task) => Promise

Add a task at the end of the queue. The returned `Promise`  will be fulfilled (rejected)
when the task is completed successfully (unsuccessfully).

This promise could be ignored as it will not lead to a `'unhandledRejection'`.

#### queue.unshift(task) => Promise

Add a task at the beginning of the queue. The returned `Promise`  will be fulfilled (rejected)
when the task is completed successfully (unsuccessfully).

This promise could be ignored as it will not lead to a `'unhandledRejection'`.

#### queue.drained() => Promise

Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker.

This promise could be ignored as it will not lead to a `'unhandledRejection'`.

## License

ISC

[ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg
[npm-badge]: https://badge.fury.io/js/fastq.svg
[npm-url]: https://badge.fury.io/js/fastq


# fill-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range)

> Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`

Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.

## Install

Install with [npm](https://www.npmjs.com/):

```sh
$ npm install --save fill-range
```

## Usage

Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_.

```js
const fill = require('fill-range');
// fill(from, to[, step, options]);

console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10
```

**Params**

* `from`: **{String|Number}** the number or letter to start with
* `to`: **{String|Number}** the number or letter to end with
* `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use.
* `options`: **{Object|Function}**: See all available [options](#options)

## Examples

By default, an array of values is returned.

**Alphabetical ranges**

```js
console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e']
console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ]
```

**Numerical ranges**

Numbers can be defined as actual numbers or strings.

```js
console.log(fill(1, 5));     //=> [ 1, 2, 3, 4, 5 ]
console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ]
```

**Negative ranges**

Numbers can be defined as actual numbers or strings.

```js
console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ]
console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ]
```

**Steps (increments)**

```js
// numerical ranges with increments
console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ]
console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ]
console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ]

// alphabetical ranges with increments
console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ]
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ]
```

## Options

### options.step

**Type**: `number` (formatted as a string or number)

**Default**: `undefined`

**Description**: The increment to use for the range. Can be used with letters or numbers.

**Example(s)**

```js
// numbers
console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ]
console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ]
console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ]

// letters
console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ]
console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ]
console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ]
```

### options.strictRanges

**Type**: `boolean`

**Default**: `false`

**Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges.

**Example(s)**

The following are all invalid:

```js
fill('1.1', '2');   // decimals not supported in ranges
fill('a', '2');     // incompatible range values
fill(1, 10, 'foo'); // invalid "step" argument
```

### options.stringify

**Type**: `boolean`

**Default**: `undefined`

**Description**: Cast all returned values to strings. By default, integers are returned as numbers.

**Example(s)**

```js
console.log(fill(1, 5));                    //=> [ 1, 2, 3, 4, 5 ]
console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ]
```

### options.toRegex

**Type**: `boolean`

**Default**: `undefined`

**Description**: Create a regex-compatible source string, instead of expanding values to an array.

**Example(s)**

```js
// alphabetical range
console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]'
// alphabetical with step
console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y'
// numerical range
console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100'
// numerical range with zero padding
console.log(fill('000001', '100000', { toRegex: true }));
//=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000'
```

### options.transform

**Type**: `function`

**Default**: `undefined`

**Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_.

**Example(s)**

```js
// add zero padding
console.log(fill(1, 5, value => String(value).padStart(4, '0')));
//=> ['0001', '0002', '0003', '0004', '0005']
```

## About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

```sh
$ npm install && npm test
```

Building docs

_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_

To generate the readme, run the following command:

```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```

### Contributors

| **Commits** | **Contributor** |
| --- | --- |
| 116 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4   | [paulmillr](https://github.com/paulmillr) |
| 2   | [realityking](https://github.com/realityking) |
| 2   | [bluelovers](https://github.com/bluelovers) |
| 1   | [edorivai](https://github.com/edorivai) |
| 1   | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |

### Author

**Jon Schlinkert**

* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)

Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)!

### License

Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).

***

_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._


v1.3.1 / 2024-09-11
==================

  * deps: encodeurl@~2.0.0

v1.3.0 / 2024-09-03
==================

  * ignore status message for HTTP/2 (#53)

v1.2.1 / 2024-09-02
==================

  * Gracefully handle when handling an error and socket is null

1.2.0 / 2022-03-22
==================

  * Remove set content headers that break response
  * deps: on-finished@2.4.1
  * deps: statuses@2.0.1
    - Rename `425 Unordered Collection` to standard `425 Too Early`

1.1.2 / 2019-05-09
==================

  * Set stricter `Content-Security-Policy` header
  * deps: parseurl@~1.3.3
  * deps: statuses@~1.5.0

1.1.1 / 2018-03-06
==================

  * Fix 404 output for bad / missing pathnames
  * deps: encodeurl@~1.0.2
    - Fix encoding `%` as last character
  * deps: statuses@~1.4.0

1.1.0 / 2017-09-24
==================

  * Use `res.headersSent` when available

1.0.6 / 2017-09-22
==================

  * deps: debug@2.6.9

1.0.5 / 2017-09-15
==================

  * deps: parseurl@~1.3.2
    - perf: reduce overhead for full URLs
    - perf: unroll the "fast-path" `RegExp`

1.0.4 / 2017-08-03
==================

  * deps: debug@2.6.8

1.0.3 / 2017-05-16
==================

  * deps: debug@2.6.7
    - deps: ms@2.0.0

1.0.2 / 2017-04-22
==================

  * deps: debug@2.6.4
    - deps: ms@0.7.3

1.0.1 / 2017-03-21
==================

  * Fix missing `</html>` in HTML document
  * deps: debug@2.6.3
    - Fix: `DEBUG_MAX_ARRAY_LENGTH`

1.0.0 / 2017-02-15
==================

  * Fix exception when `err` cannot be converted to a string
  * Fully URL-encode the pathname in the 404 message
  * Only include the pathname in the 404 message
  * Send complete HTML document
  * Set `Content-Security-Policy: default-src 'self'` header
  * deps: debug@2.6.1
    - Allow colors in workers
    - Deprecated `DEBUG_FD` environment variable set to `3` or higher
    - Fix error when running under React Native
    - Use same color for same namespace
    - deps: ms@0.7.2

0.5.1 / 2016-11-12
==================

  * Fix exception when `err.headers` is not an object
  * deps: statuses@~1.3.1
  * perf: hoist regular expressions
  * perf: remove duplicate validation path

0.5.0 / 2016-06-15
==================

  * Change invalid or non-numeric status code to 500
  * Overwrite status message to match set status code
  * Prefer `err.statusCode` if `err.status` is invalid
  * Set response headers from `err.headers` object
  * Use `statuses` instead of `http` module for status messages
    - Includes all defined status messages

0.4.1 / 2015-12-02
==================

  * deps: escape-html@~1.0.3
    - perf: enable strict mode
    - perf: optimize string replacement
    - perf: use faster string coercion

0.4.0 / 2015-06-14
==================

  * Fix a false-positive when unpiping in Node.js 0.8
  * Support `statusCode` property on `Error` objects
  * Use `unpipe` module for unpiping requests
  * deps: escape-html@1.0.2
  * deps: on-finished@~2.3.0
    - Add defined behavior for HTTP `CONNECT` requests
    - Add defined behavior for HTTP `Upgrade` requests
    - deps: ee-first@1.1.1
  * perf: enable strict mode
  * perf: remove argument reassignment

0.3.6 / 2015-05-11
==================

  * deps: debug@~2.2.0
    - deps: ms@0.7.1

0.3.5 / 2015-04-22
==================

  * deps: on-finished@~2.2.1
    - Fix `isFinished(req)` when data buffered

0.3.4 / 2015-03-15
==================

  * deps: debug@~2.1.3
    - Fix high intensity foreground color for bold
    - deps: ms@0.7.0

0.3.3 / 2015-01-01
==================

  * deps: debug@~2.1.1
  * deps: on-finished@~2.2.0

0.3.2 / 2014-10-22
==================

  * deps: on-finished@~2.1.1
    - Fix handling of pipelined requests

0.3.1 / 2014-10-16
==================

  * deps: debug@~2.1.0
    - Implement `DEBUG_FD` env variable support

0.3.0 / 2014-09-17
==================

  * Terminate in progress response only on error
  * Use `on-finished` to determine request status

0.2.0 / 2014-09-03
==================

  * Set `X-Content-Type-Options: nosniff` header
  * deps: debug@~2.0.0

0.1.0 / 2014-07-16
==================

  * Respond after request fully read
    - prevents hung responses and socket hang ups
  * deps: debug@1.0.4

0.0.3 / 2014-07-11
==================

  * deps: debug@1.0.3
    - Add support for multiple wildcards in namespaces

0.0.2 / 2014-06-19
==================

  * Handle invalid status codes

0.0.1 / 2014-06-05
==================

  * deps: debug@1.0.2

0.0.0 / 2014-06-05
==================

  * Extracted from connect/express


# finalhandler

[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-image]][node-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]

Node.js function to invoke as the final step to respond to HTTP request.

## Installation

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```sh
$ npm install finalhandler
```

## API

```js
var finalhandler = require('finalhandler')
```

### finalhandler(req, res, [options])

Returns function to be invoked as the final step for the given `req` and `res`.
This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will
write out a 404 response to the `res`. If it is truthy, an error response will
be written out to the `res` or `res` will be terminated if a response has already
started.

When an error is written, the following information is added to the response:

  * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If
    this value is outside the 4xx or 5xx range, it will be set to 500.
  * The `res.statusMessage` is set according to the status code.
  * The body will be the HTML of the status code message if `env` is
    `'production'`, otherwise will be `err.stack`.
  * Any headers specified in an `err.headers` object.

The final handler will also unpipe anything from `req` when it is invoked.

#### options.env

By default, the environment is determined by `NODE_ENV` variable, but it can be
overridden by this option.

#### options.onerror

Provide a function to be called with the `err` when it exists. Can be used for
writing errors to a central location without excessive function generation. Called
as `onerror(err, req, res)`.

## Examples

### always 404

```js
var finalhandler = require('finalhandler')
var http = require('http')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  done()
})

server.listen(3000)
```

### perform simple action

```js
var finalhandler = require('finalhandler')
var fs = require('fs')
var http = require('http')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res)

  fs.readFile('index.html', function (err, buf) {
    if (err) return done(err)
    res.setHeader('Content-Type', 'text/html')
    res.end(buf)
  })
})

server.listen(3000)
```

### use with middleware-style functions

```js
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

var serve = serveStatic('public')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  serve(req, res, done)
})

server.listen(3000)
```

### keep log of all errors

```js
var finalhandler = require('finalhandler')
var fs = require('fs')
var http = require('http')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res, { onerror: logerror })

  fs.readFile('index.html', function (err, buf) {
    if (err) return done(err)
    res.setHeader('Content-Type', 'text/html')
    res.end(buf)
  })
})

server.listen(3000)

function logerror (err) {
  console.error(err.stack || err.toString())
}
```

## License

[MIT](LICENSE)

[npm-image]: https://img.shields.io/npm/v/finalhandler.svg
[npm-url]: https://npmjs.org/package/finalhandler
[node-image]: https://img.shields.io/node/v/finalhandler.svg
[node-url]: https://nodejs.org/en/download
[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg
[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master
[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg
[downloads-url]: https://npmjs.org/package/finalhandler
[github-actions-ci-image]: https://github.com/pillarjs/finalhandler/actions/workflows/ci.yml/badge.svg
[github-actions-ci-url]: https://github.com/pillarjs/finalhandler/actions/workflows/ci.yml


# Security Policies and Procedures

## Reporting a Bug

The `finalhandler` team and community take all security bugs seriously. Thank
you for improving the security of Express. We appreciate your efforts and
responsible disclosure and will make every effort to acknowledge your
contributions.

Report security bugs by emailing the current owner(s) of `finalhandler`. This
information can be found in the npm registry using the command
`npm owner ls finalhandler`.
If unsure or unable to get the information from the above, open an issue
in the [project issue tracker](https://github.com/pillarjs/finalhandler/issues)
asking for the current contact information.

To ensure the timely response to your report, please ensure that the entirety
of the report is contained within the email body and not solely behind a web
link or an attachment.

At least one owner will acknowledge your email within 48 hours, and will send a
more detailed response within 48 hours indicating the next steps in handling
your report. After the initial reply to your report, the owners will
endeavor to keep you informed of the progress towards a fix and full
announcement, and may ask for additional information or guidance.


# foreground-child

Run a child as if it's the foreground process. Give it stdio. Exit
when it exits.

Mostly this module is here to support some use cases around
wrapping child processes for test coverage and such. But it's
also generally useful any time you want one program to execute
another as if it's the "main" process, for example, if a program
takes a `--cmd` argument to execute in some way.

## USAGE

```js
import { foregroundChild } from 'foreground-child'
// hybrid module, this also works:
// const { foregroundChild } = require('foreground-child')

// cats out this file
const child = foregroundChild('cat', [__filename])

// At this point, it's best to just do nothing else.
// return or whatever.
// If the child gets a signal, or just exits, then this
// parent process will exit in the same way.
```

You can provide custom spawn options by passing an object after
the program and arguments:

```js
const child = foregroundChild(`cat ${__filename}`, { shell: true })
```

A callback can optionally be provided, if you want to perform an
action before your foreground-child exits:

```js
const child = foregroundChild('cat', [__filename], spawnOptions, () => {
  doSomeActions()
})
```

The callback can return a Promise in order to perform
asynchronous actions. If the callback does not return a promise,
then it must complete its actions within a single JavaScript
tick.

```js
const child = foregroundChild('cat', [__filename], async () => {
  await doSomeAsyncActions()
})
```

If the callback throws or rejects, then it will be unhandled, and
node will exit in error.

If the callback returns a string value, then that will be used as
the signal to exit the parent process. If it returns a number,
then that number will be used as the parent exit status code. If
it returns boolean `false`, then the parent process will not be
terminated. If it returns `undefined`, then it will exit with the
same signal/code as the child process.

## Caveats

The "normal" standard IO file descriptors (0, 1, and 2 for stdin,
stdout, and stderr respectively) are shared with the child process.
Additionally, if there is an IPC channel set up in the parent, then
messages are proxied to the child on file descriptor 3.

In Node, it's possible to also map arbitrary file descriptors
into a child process. In these cases, foreground-child will not
map the file descriptors into the child. If file descriptors 0,
1, or 2 are used for the IPC channel, then strange behavior may
happen (like printing IPC messages to stderr, for example).

Note that a SIGKILL will always kill the parent process, but
will not proxy the signal to the child process, because SIGKILL
cannot be caught. In order to address this, a special "watchdog"
child process is spawned which will send a SIGKILL to the child
process if it does not terminate within half a second after the
watchdog receives a SIGHUP due to its parent terminating.

On Windows, issuing a `process.kill(process.pid, signal)` with a
fatal termination signal may cause the process to exit with a `1`
status code rather than reporting the signal properly. This
module tries to do the right thing, but on Windows systems, you
may see that incorrect result. There is as far as I'm aware no
workaround for this.

## util: `foreground-child/proxy-signals`

If you just want to proxy the signals to a child process that the
main process receives, you can use the `proxy-signals` export
from this package.

```js
import { proxySignals } from 'foreground-child/proxy-signals'

const childProcess = spawn('command', ['some', 'args'])
proxySignals(childProcess)
```

Now, any fatal signal received by the current process will be
proxied to the child process.

It doesn't go in the other direction; ie, signals sent to the
child process will not affect the parent. For that, listen to the
child `exit` or `close` events, and handle them appropriately.

## util: `foreground-child/watchdog`

If you are spawning a child process, and want to ensure that it
isn't left dangling if the parent process exits, you can use the
watchdog utility exported by this module.

```js
import { watchdog } from 'foreground-child/watchdog'

const childProcess = spawn('command', ['some', 'args'])
const watchdogProcess = watchdog(childProcess)

// watchdogProcess is a reference to the process monitoring the
// parent and child. There's usually no reason to do anything
// with it, as it's silent and will terminate
// automatically when it's no longer needed.
```


0.2.0 / 2021-05-31
==================

  * Use `req.socket` over deprecated `req.connection`

0.1.2 / 2017-09-14
==================

  * perf: improve header parsing
  * perf: reduce overhead when no `X-Forwarded-For` header

0.1.1 / 2017-09-10
==================

  * Fix trimming leading / trailing OWS
  * perf: hoist regular expression

0.1.0 / 2014-09-21
==================

  * Initial release


# forwarded

[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]

Parse HTTP X-Forwarded-For header

## Installation

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```sh
$ npm install forwarded
```

## API

```js
var forwarded = require('forwarded')
```

### forwarded(req)

```js
var addresses = forwarded(req)
```

Parse the `X-Forwarded-For` header from the request. Returns an array
of the addresses, including the socket address for the `req`, in reverse
order (i.e. index `0` is the socket address and the last index is the
furthest address, typically the end-user).

## Testing

```sh
$ npm test
```

## License

[MIT](LICENSE)

[ci-image]: https://badgen.net/github/checks/jshttp/forwarded/master?label=ci
[ci-url]: https://github.com/jshttp/forwarded/actions?query=workflow%3Aci
[npm-image]: https://img.shields.io/npm/v/forwarded.svg
[npm-url]: https://npmjs.org/package/forwarded
[node-version-image]: https://img.shields.io/node/v/forwarded.svg
[node-version-url]: https://nodejs.org/en/download/
[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master
[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg
[downloads-url]: https://npmjs.org/package/forwarded