Skip to content

Latest commit

 

History

History
42 lines (29 loc) · 1.37 KB

prefer-json-parse-buffer.md

File metadata and controls

42 lines (29 loc) · 1.37 KB

Prefer reading a JSON file as a buffer

🚫 This rule is disabled in the ✅ recommended config.

🔧 This rule is automatically fixable by the --fix CLI option.

When reading and parsing a JSON file, it's unnecessary to read it as a string, because JSON.parse() can also parse Buffer.

Passing in a buffer may not be performant and is not compatible with TypeScript.

Fail

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

Pass

const packageJson = JSON.parse(await fs.readFile('./package.json'));
const promise = fs.readFile('./package.json', {encoding: 'utf8', signal});
const packageJson = JSON.parse(await promise);
const data = JSON.parse(await fs.readFile('./file.json', 'buffer'));
const data = JSON.parse(await fs.readFile('./file.json', 'gbk'));