refactor: prefer fs.readJSON over readFile.then(JSON.parse) (#7186)

* refactor: prefer fs.readJSON over readFile.then(JSON.parse)

* refactor: use promises
This commit is contained in:
Joshua Chen 2022-04-17 12:50:09 +08:00 committed by GitHub
parent 674a77f02d
commit 200009008b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 27 additions and 33 deletions

View file

@ -27,12 +27,8 @@ type PackageJsonFile = {
async function getPackagesJsonFiles(): Promise<PackageJsonFile[]> { async function getPackagesJsonFiles(): Promise<PackageJsonFile[]> {
const files = await Globby('packages/*/package.json'); const files = await Globby('packages/*/package.json');
return Promise.all( return Promise.all(
files.map(async (file) => ({ files.map((file) => fs.readJSON(file).then((content) => ({file, content}))),
file,
content: JSON.parse(await fs.readFile(file, 'utf8')),
})),
); );
} }

View file

@ -37,8 +37,8 @@ async function generateTemplateExample(template) {
); );
// read the content of the package.json // read the content of the package.json
const templatePackageJson = JSON.parse( const templatePackageJson = await fs.readJSON(
await fs.readFile(`examples/${template}/package.json`, 'utf8'), `examples/${template}/package.json`,
); );
// attach the dev script which would be used in code sandbox by default // attach the dev script which would be used in code sandbox by default

View file

@ -103,8 +103,7 @@ function isValidGitRepoUrl(gitRepoUrl: string) {
} }
async function updatePkg(pkgPath: string, obj: {[key: string]: unknown}) { async function updatePkg(pkgPath: string, obj: {[key: string]: unknown}) {
const content = await fs.readFile(pkgPath, 'utf-8'); const pkg = await fs.readJSON(pkgPath);
const pkg = JSON.parse(content);
const newPkg = Object.assign(pkg, obj); const newPkg = Object.assign(pkg, obj);
await fs.outputFile(pkgPath, `${JSON.stringify(newPkg, null, 2)}\n`); await fs.outputFile(pkgPath, `${JSON.stringify(newPkg, null, 2)}\n`);

View file

@ -443,8 +443,8 @@ async function migrateBlogFiles(context: MigrationContext) {
async function handleVersioning(context: MigrationContext) { async function handleVersioning(context: MigrationContext) {
const {siteDir, newDir} = context; const {siteDir, newDir} = context;
if (await fs.pathExists(path.join(siteDir, 'versions.json'))) { if (await fs.pathExists(path.join(siteDir, 'versions.json'))) {
const loadedVersions: string[] = JSON.parse( const loadedVersions: string[] = await fs.readJSON(
await fs.readFile(path.join(siteDir, 'versions.json'), 'utf-8'), path.join(siteDir, 'versions.json'),
); );
await fs.copyFile( await fs.copyFile(
path.join(siteDir, 'versions.json'), path.join(siteDir, 'versions.json'),
@ -542,7 +542,7 @@ async function migrateVersionedSidebar(
`version-${version}-sidebars.json`, `version-${version}-sidebars.json`,
); );
try { try {
sidebarEntries = JSON.parse(await fs.readFile(sidebarPath, 'utf-8')); sidebarEntries = await fs.readJSON(sidebarPath);
} catch { } catch {
sidebars.push({version, entries: sidebars[i - 1]!.entries}); sidebars.push({version, entries: sidebars[i - 1]!.entries});
return; return;

View file

@ -17,22 +17,24 @@ jest.setTimeout(15000);
describe('theme translations', () => { describe('theme translations', () => {
it('has base messages files contain EXACTLY all the translations extracted from the theme. Please run "yarn workspace @docusaurus/theme-translations update" to keep base messages files up-to-date', async () => { it('has base messages files contain EXACTLY all the translations extracted from the theme. Please run "yarn workspace @docusaurus/theme-translations update" to keep base messages files up-to-date', async () => {
const baseMessagesDirPath = path.join(__dirname, '../base'); const baseMessagesDirPath = path.join(__dirname, '../base');
const baseMessages = Object.fromEntries( const baseMessages = await fs
await Promise.all( .readdir(baseMessagesDirPath)
( .then((files) =>
await fs.readdir(baseMessagesDirPath) Promise.all(
).map(async (baseMessagesFile) => files.map(
Object.entries( (baseMessagesFile): Promise<{[key: string]: string}> =>
(await fs.readJSON( fs.readJSON(path.join(baseMessagesDirPath, baseMessagesFile)),
path.join(baseMessagesDirPath, baseMessagesFile),
'utf-8',
)) as {[key: string]: string},
), ),
), ),
).then((translations) => )
translations.flat().filter(([key]) => !key.endsWith('___DESCRIPTION')), .then((translations) =>
), Object.fromEntries(
); translations
.map(Object.entries)
.flat()
.filter(([key]) => !key.endsWith('___DESCRIPTION')),
),
);
const codeMessages = _.mapValues( const codeMessages = _.mapValues(
await extractThemeCodeMessages(), await extractThemeCodeMessages(),
(translation) => translation.message, (translation) => translation.message,

View file

@ -50,8 +50,7 @@ export async function readDefaultCodeTranslationMessages({
const filePath = path.resolve(dirPath, localeToTry, `${name}.json`); const filePath = path.resolve(dirPath, localeToTry, `${name}.json`);
if (await fs.pathExists(filePath)) { if (await fs.pathExists(filePath)) {
const fileContent = await fs.readFile(filePath, 'utf8'); return fs.readJSON(filePath);
return JSON.parse(fileContent);
} }
} }

View file

@ -55,7 +55,7 @@ async function readMessagesFile(filePath) {
logger.info`File path=${filePath} not found. Creating new translation base file.`; logger.info`File path=${filePath} not found. Creating new translation base file.`;
await fs.outputFile(filePath, '{}\n'); await fs.outputFile(filePath, '{}\n');
} }
return JSON.parse((await fs.readFile(filePath)).toString()); return fs.readJSON(filePath);
} }
/** /**

View file

@ -111,9 +111,7 @@ async function doRender(locals: Locals & {path: string}) {
const {generatedFilesDir} = locals; const {generatedFilesDir} = locals;
const manifestPath = path.join(generatedFilesDir, 'client-manifest.json'); const manifestPath = path.join(generatedFilesDir, 'client-manifest.json');
const manifest: Manifest = JSON.parse( const manifest: Manifest = await fs.readJSON(manifestPath);
await fs.readFile(manifestPath, 'utf8'),
);
// Get all required assets for this particular page based on client // Get all required assets for this particular page based on client
// manifest information. // manifest information.

View file

@ -58,7 +58,7 @@ async function readTranslationFileContent(
): Promise<TranslationFileContent | undefined> { ): Promise<TranslationFileContent | undefined> {
if (await fs.pathExists(filePath)) { if (await fs.pathExists(filePath)) {
try { try {
const content = JSON.parse(await fs.readFile(filePath, 'utf8')); const content = await fs.readJSON(filePath);
ensureTranslationFileContent(content); ensureTranslationFileContent(content);
return content; return content;
} catch (err) { } catch (err) {