# Node.js API
While ESLint is designed to be run on the command line, it's possible to use ESLint programmatically through the Node.js API. The purpose of the Node.js API is to allow plugin and tool authors to use the ESLint functionality directly, without going through the command line interface.
**Note:** Use undocumented parts of the API at your own risk. Only those parts that are specifically mentioned in this document are approved for use and will remain stable and reliable. Anything left undocumented is unstable and may change or be removed at any point.
## Table of Contents
* [ESLint]
* [constructor()][eslint-constructor]
* [lintFiles()][eslint-lintfiles]
* [lintText()][eslint-linttext]
* [getRulesMetaForResults()][eslint-getrulesmetaforresults]
* [calculateConfigForFile()][eslint-calculateconfigforfile]
* [isPathIgnored()][eslint-ispathignored]
* [loadFormatter()][eslint-loadformatter]
* [static version][eslint-version]
* [static outputFixes()][eslint-outputfixes]
* [static getErrorResults()][eslint-geterrorresults]
* [LintResult type][lintresult]
* [LintMessage type][lintmessage]
* [EditInfo type][editinfo]
* [Formatter type][formatter]
* [SourceCode](#sourcecode)
* [splitLines()](#sourcecodesplitlines)
* [Linter](#linter)
* [verify()](#linterverify)
* [verifyAndFix()](#linterverifyandfix)
* [defineRule()](#linterdefinerule)
* [defineRules()](#linterdefinerules)
* [getRules()](#lintergetrules)
* [defineParser()](#linterdefineparser)
* [version](#linterversionlinterversion)
* [RuleTester](#ruletester)
* [Customizing RuleTester](#customizing-ruletester)
---
## ESLint class
The `ESLint` class is the primary class to use in Node.js applications.
This class depends on the Node.js `fs` module and the file system, so you cannot use it in browsers. If you want to lint code on browsers, use the [Linter](#linter) class instead.
Here's a simple example of using the `ESLint` class:
```js
const { ESLint } = require("eslint");
(async function main() {
// 1. Create an instance.
const eslint = new ESLint();
// 2. Lint files.
const results = await eslint.lintFiles(["lib/**/*.js"]);
// 3. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 4. Output it.
console.log(resultText);
})().catch((error) => {
process.exitCode = 1;
console.error(error);
});
```
And here is an example that autofixes lint problems:
```js
const { ESLint } = require("eslint");
(async function main() {
// 1. Create an instance with the `fix` option.
const eslint = new ESLint({ fix: true });
// 2. Lint files. This doesn't modify target files.
const results = await eslint.lintFiles(["lib/**/*.js"]);
// 3. Modify the files with the fixed code.
await ESLint.outputFixes(results);
// 4. Format the results.
const formatter = await eslint.loadFormatter("stylish");
const resultText = formatter.format(results);
// 5. Output it.
console.log(resultText);
})().catch((error) => {
process.exitCode = 1;
console.error(error);
});
```
### ◆ new ESLint(options)
```js
const eslint = new ESLint(options);
```
Create a new `ESLint` instance.
#### Parameters
The `ESLint` constructor takes an `options` object. If you omit the `options` object then it uses default values for all options. The `options` object has the following properties.
##### File Enumeration
* `options.cwd` (`string`)
Default is `process.cwd()`. The working directory. This must be an absolute path.
* `options.errorOnUnmatchedPattern` (`boolean`)
Default is `true`. Unless set to `false`, the [`eslint.lintFiles()`][eslint-lintfiles] method will throw an error when no target files are found.
* `options.extensions` (`string[] | null`)
Default is `null`. If you pass directory paths to the [`eslint.lintFiles()`][eslint-lintfiles] method, ESLint checks the files in those directories that have the given extensions. For example, when passing the `src/` directory and `extensions` is `[".js", ".ts"]`, ESLint will lint `*.js` and `*.ts` files in `src/`. If `extensions` is `null`, ESLint checks `*.js` files and files that match `overrides[].files` patterns in your configuration. **Note:** This option only applies when you pass directory paths to the [`eslint.lintFiles()`][eslint-lintfiles] method. If you pass glob patterns like `lib/**/*`, ESLint will lint all files matching the glob pattern regardless of extension.
* `options.globInputPaths` (`boolean`)
Default is `true`. If `false` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method doesn't interpret glob patterns.
* `options.ignore` (`boolean`)
Default is `true`. If `false` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method doesn't respect `.eslintignore` files or `ignorePatterns` in your configuration.
* `options.ignorePath` (`string | null`)
Default is `null`. The path to a file ESLint uses instead of `$CWD/.eslintignore`. If a path is present and the file doesn't exist, this constructor will throw an error.
##### Linting
* `options.allowInlineConfig` (`boolean`)
Default is `true`. If `false` is present, ESLint suppresses directive comments in source code. If this option is `false`, it overrides the `noInlineConfig` setting in your configurations.
* `options.baseConfig` (`ConfigData | null`)
Default is `null`. [Configuration object], extended by all configurations used with this instance. You can use this option to define the default settings that will be used if your configuration files don't configure it.
* `options.overrideConfig` (`ConfigData | null`)
Default is `null`. [Configuration object], overrides all configurations used with this instance. You can use this option to define the settings that will be used even if your configuration files configure it.
* `options.overrideConfigFile` (`string | null`)
Default is `null`. The path to a configuration file, overrides all configurations used with this instance. The `options.overrideConfig` option is applied after this option is applied.
* `options.plugins` (`Record | null`)
Default is `null`. The plugin implementations that ESLint uses for the `plugins` setting of your configuration. This is a map-like object. Those keys are plugin IDs and each value is implementation.
* `options.reportUnusedDisableDirectives` (`"error" | "warn" | "off" | null`)
Default is `null`. The severity to report unused eslint-disable directives. If this option is a severity, it overrides the `reportUnusedDisableDirectives` setting in your configurations.
* `options.resolvePluginsRelativeTo` (`string` | `null`)
Default is `null`. The path to a directory where plugins should be resolved from. If `null` is present, ESLint loads plugins from the location of the configuration file that contains the plugin setting. If a path is present, ESLint loads all plugins from there.
* `options.rulePaths` (`string[]`)
Default is `[]`. An array of paths to directories to load custom rules from.
* `options.useEslintrc` (`boolean`)
Default is `true`. If `false` is present, ESLint doesn't load configuration files (`.eslintrc.*` files). Only the configuration of the constructor options is valid.
##### Autofix
* `options.fix` (`boolean | (message: LintMessage) => boolean`)
Default is `false`. If `true` is present, the [`eslint.lintFiles()`][eslint-lintfiles] and [`eslint.lintText()`][eslint-linttext] methods work in autofix mode. If a predicate function is present, the methods pass each lint message to the function, then use only the lint messages for which the function returned `true`.
* `options.fixTypes` (`("directive" | "problem" | "suggestion" | "layout")[] | null`)
Default is `null`. The types of the rules that the [`eslint.lintFiles()`][eslint-lintfiles] and [`eslint.lintText()`][eslint-linttext] methods use for autofix.
##### Cache-related
* `options.cache` (`boolean`)
Default is `false`. If `true` is present, the [`eslint.lintFiles()`][eslint-lintfiles] method caches lint results and uses it if each target file is not changed. Please mind that ESLint doesn't clear the cache when you upgrade ESLint plugins. In that case, you have to remove the cache file manually. The [`eslint.lintText()`][eslint-linttext] method doesn't use caches even if you pass the `options.filePath` to the method.
* `options.cacheLocation` (`string`)
Default is `.eslintcache`. The [`eslint.lintFiles()`][eslint-lintfiles] method writes caches into this file.
* `options.cacheStrategy` (`string`)
Default is `"metadata"`. Strategy for the cache to use for detecting changed files. Can be either `"metadata"` or `"content"`.
### ◆ eslint.lintFiles(patterns)
```js
const results = await eslint.lintFiles(patterns);
```
This method lints the files that match the glob patterns and then returns the results.
#### Parameters
* `patterns` (`string | string[]`)
The lint target files. This can contain any of file paths, directory paths, and glob patterns.
#### Return Value
* (`Promise`)
The promise that will be fulfilled with an array of [LintResult] objects.
### ◆ eslint.lintText(code, options)
```js
const results = await eslint.lintText(code, options);
```
This method lints the given source code text and then returns the results.
By default, this method uses the configuration that applies to files in the current working directory (the `cwd` constructor option). If you want to use a different configuration, pass `options.filePath`, and ESLint will load the same configuration that [`eslint.lintFiles()`][eslint-lintfiles] would use for a file at `options.filePath`.
If the `options.filePath` value is configured to be ignored, this method returns an empty array. If the `options.warnIgnored` option is set along with the `options.filePath` option, this method returns a [LintResult] object. In that case, the result may contain a warning that indicates the file was ignored.
#### Parameters
The second parameter `options` is omittable.
* `code` (`string`)
The source code text to check.
* `options.filePath` (`string`)
Optional. The path to the file of the source code text. If omitted, the `result.filePath` becomes the string `""`.
* `options.warnIgnored` (`boolean`)
Optional. If `true` is present and the `options.filePath` is a file ESLint should ignore, this method returns a lint result contains a warning message.
#### Return Value
* (`Promise`)
The promise that will be fulfilled with an array of [LintResult] objects. This is an array (despite there being only one lint result) in order to keep the interfaces between this and the [`eslint.lintFiles()`][eslint-lintfiles] method similar.
### ◆ eslint.getRulesMetaForResults(results)
```js
const results = await eslint.lintFiles(patterns);
const rulesMeta = eslint.getRulesMetaForResults(results);
```
This method returns an object containing meta information for each rule that triggered a lint error in the given `results`.
#### Parameters
* `results` (`LintResult[]`)
An array of [LintResult] objects returned from a call to `ESLint#lintFiles()` or `ESLint#lintText()`.
#### Return Value
* (`Object`)
An object whose property names are the rule IDs from the `results` and whose property values are the rule's meta information (if available).
### ◆ eslint.calculateConfigForFile(filePath)
```js
const config = await eslint.calculateConfigForFile(filePath);
```
This method calculates the configuration for a given file, which can be useful for debugging purposes.
* It resolves and merges `extends` and `overrides` settings into the top level configuration.
* It resolves the `parser` setting to absolute paths.
* It normalizes the `plugins` setting to align short names. (e.g., `eslint-plugin-foo` → `foo`)
* It adds the `processor` setting if a legacy file extension processor is matched.
* It doesn't interpret the `env` setting to the `globals` and `parserOptions` settings, so the result object contains the `env` setting as is.
#### Parameters
* `filePath` (`string`)
The path to the file whose configuration you would like to calculate. Directory paths are forbidden because ESLint cannot handle the `overrides` setting.
#### Return Value
* (`Promise