Skip to content

Latest commit

Β 

History

History
56 lines (36 loc) Β· 1.88 KB

File metadata and controls

56 lines (36 loc) Β· 1.88 KB

consistent-json-file-read

πŸ“ Enforce consistent JSON file reads before JSON.parse().

πŸ’ΌπŸš« This rule is enabled in the βœ… recommended config. This rule is disabled in the β˜‘οΈ unopinionated config.

πŸ”§ This rule is automatically fixable by the --fix CLI option.

When reading and parsing a JSON file, consistently read it using the configured style. By default, the rule prefers reading it as a string.

The default keeps the code compatible with TypeScript, where JSON.parse() accepts a string.

The rule only checks and fixes direct no-option reads and option objects where encoding is the only property. Reads with additional options are left unchanged to avoid dropping options.

Examples

// ❌
const packageJson = JSON.parse(await fs.readFile('./package.json'));

// ❌
const promise = fs.readFile('./package.json');
const packageJson = JSON.parse(await promise);

// βœ…
const packageJson = JSON.parse(await fs.readFile('./package.json', 'utf8'));
// βœ…
const promise = fs.readFile('./package.json', {encoding: 'utf8', signal});
const packageJson = JSON.parse(await promise);

Options

Type: 'string' | 'buffer'

Default: 'string'

buffer

Prefer reading JSON files as buffers.

// eslint unicorn/consistent-json-file-read: ["error", "buffer"]

// ❌
const packageJson = JSON.parse(await fs.readFile('./package.json', 'utf8'));

// βœ…
const packageJson = JSON.parse(await fs.readFile('./package.json'));