Skip to content

Commit

Permalink
refactor: Use fs.writeFile instead of fs-extra
Browse files Browse the repository at this point in the history
  • Loading branch information
vio committed Sep 25, 2023
1 parent 1f381f3 commit e7948e0
Show file tree
Hide file tree
Showing 9 changed files with 1,231 additions and 1,327 deletions.
2,493 changes: 1,198 additions & 1,295 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion packages/cli-utils/__mocks__/fs.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export { fs } from 'memfs';
const { vol } = require('memfs');

module.exports = vol;
4 changes: 2 additions & 2 deletions packages/cli-utils/__mocks__/fs/promises.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { fs } from 'memfs';
const { vol } = require('memfs');

export default fs.promises;
module.exports = vol.promises;
2 changes: 1 addition & 1 deletion packages/cli-utils/src/__tests__/reports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const SOURCE_BASELINE = {
],
};

describe('generateAssets', () => {
describe('generateReports', () => {
test('should generate reports with default options', async () => {
const reports = await generateReports(SOURCE_CURRENT, {});

Expand Down
13 changes: 0 additions & 13 deletions packages/cli-utils/src/baseline.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import path from 'path';
import fs from 'fs/promises';
import findCacheDir from 'find-cache-dir';

export const BASELINE_STATS_DIR =
Expand Down Expand Up @@ -36,15 +35,3 @@ export const getBaselineRelativePath = (
const absoluteFilepath = getBaselinePath(outputPath, outputDir, filepath);
return path.relative(path.join(outputPath, outputDir), absoluteFilepath);
};

export async function readBaseline(baselineFilepath: string): Promise<object> {
const file = await fs.readFile(baselineFilepath, 'utf-8');
return JSON.parse(file);
}

export async function writeBaseline(
baselineFilepath: string,
data: Record<string, unknown>,
): Promise<void> {
return fs.writeFile(baselineFilepath, JSON.stringify(data));
}
23 changes: 19 additions & 4 deletions packages/cli-utils/src/fs.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
import { createReadStream } from 'fs';
import { writeFile, stat } from 'fs/promises';
import { parser } from 'stream-json';
import { chain } from 'stream-chain';
import Asm from 'stream-json/Assembler';

export const readJSONStream = <T = unknown>(filepath: string): Promise<T> => {
const pipeline = chain([createReadStream(filepath), parser()]);
export const readJSONStream = async <T = unknown>(filepath: string): Promise<T> => {
// Check if the file exists and throw error before creating a stream
await stat(filepath);

const readStream = createReadStream(filepath);
const pipeline = chain([readStream, parser()]);
const asm = Asm.connectTo(pipeline);

return new Promise((fulfill) => {
asm.on('done', (data) => fulfill(data.current));
return new Promise((resolve, reject) => {
asm.on('done', (data) => {
if (data.current) {
resolve(data.current);
} else {
reject(new Error('Invalid JSON file'));
}
});
});
};

export async function writeJSON(filepath: string, data: Record<string, unknown>): Promise<void> {
return writeFile(filepath, JSON.stringify(data));
}
7 changes: 4 additions & 3 deletions packages/cli-utils/src/reports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import filter from '@bundle-stats/plugin-webpack-filter';

import * as TEXT from './text';
import { createArtifacts } from './create-artifacts';
import { getBaselinePath, getBaselineRelativePath, readBaseline } from './baseline';
import { readJSONStream } from './fs';
import { getBaselinePath, getBaselineRelativePath } from './baseline';

export function getReportInfo(report: any): any {
return report?.insights?.webpack?.assetsSizeTotal?.data;
Expand Down Expand Up @@ -110,8 +111,8 @@ export const generateReports = async (

if (compare) {
try {
const baselineStatsData = await readBaseline(baselineAbsolutePath);
baselineStats = filter(baselineStatsData);
const baselineStatsData = await readJSONStream(baselineAbsolutePath);
baselineStats = filter(baselineStatsData as any);

if (!options.silent) {
logger.info(`${TEXT.BASELINE_READING} ${baselinePath}`);
Expand Down
2 changes: 0 additions & 2 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,13 @@
"@bundle-stats/utils": "^4.7.1",
"boxen": "^5.0.0",
"core-js": "^3.21.0",
"fs-extra": "^11.0.0",
"listr2": "^5.0.1",
"lodash": "^4.17.0",
"update-notifier": "^5.0.0",
"yargs": "^17.4.0"
},
"devDependencies": {
"@playwright/test": "1.38.1",
"@types/fs-extra": "^11.0.0",
"@types/listr": "^0.14.4",
"@types/yargs": "^17.0.20",
"http-server": "14.1.1",
Expand Down
10 changes: 4 additions & 6 deletions packages/cli/src/run.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable no-console */
import path from 'path';
import { outputFile } from 'fs-extra';
import { Listr } from 'listr2';
import { get } from 'lodash';
import boxen from 'boxen';
Expand All @@ -25,9 +24,8 @@ import {
getBaselinePath,
getBaselineRelativePath,
getReportInfo,
readBaseline,
readJSONStream,
writeBaseline,
writeJSON,
} from '@bundle-stats/cli-utils';

import LOCALES from './locales.json';
Expand Down Expand Up @@ -105,7 +103,7 @@ export default async function run(options: RunOptions): Promise<void> {
let baselineStats = {};

try {
baselineStats = await readBaseline(baselineAbsolutePath);
baselineStats = await readJSONStream(baselineAbsolutePath);
ctx.baselineStats = baselineStats;
} catch (err) {
return TEXT.BASELINE_MISSING;
Expand All @@ -120,7 +118,7 @@ export default async function run(options: RunOptions): Promise<void> {
const stats = get(ctx, 'sources[0]webpack');
const filteredWebpackStats = webpackFilter(stats) as Record<string, unknown>;

return writeBaseline(baselineAbsolutePath, filteredWebpackStats).then(() => {
return writeJSON(baselineAbsolutePath, filteredWebpackStats).then(() => {
// eslint-disable-next-line no-param-reassign
task.title = `${task.title} (${baselinePath})`;
});
Expand Down Expand Up @@ -148,7 +146,7 @@ export default async function run(options: RunOptions): Promise<void> {
title: filename,
task: async () => {
const filepath = path.join(outDir, filename);
await outputFile(filepath, output);
await writeJSON(filepath, output);

ctx.output = [...(ctx.output ? ctx.output : []), filepath];
},
Expand Down

0 comments on commit e7948e0

Please sign in to comment.