Versions
Index

Node.js API Reference

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.

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 class instead.

Here’s a simple example of using the ESLint class:

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);
});

Here’s an example that autofixes lint problems:

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);
});

And here is an example of using the ESLint class with lintText API:

const { ESLint } = require("eslint");

const testCode = `
  const name = "eslint";
  if(true) {
    console.log("constant condition warning")
  };
`;

(async function main() {
	// 1. Create an instance
	const eslint = new ESLint({
		overrideConfigFile: true,
		overrideConfig: {
			languageOptions: {
				ecmaVersion: 2018,
				sourceType: "commonjs",
			},
		},
	});

	// 2. Lint text.
	const results = await eslint.lintText(testCode);

	// 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);
});