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'));
โšก