From 0bcd628ec30e899df9828cab71e79c7ee1daba3e Mon Sep 17 00:00:00 2001 From: Geoffrey <11151445+g3offrey@users.noreply.github.com> Date: Tue, 4 Jan 2022 16:29:16 +0100 Subject: [PATCH] Avoid writing to output files when no changes (#6550) * fix(cli): avoid write same output when no changes * generalize outputFile This function will check a cache, it will only write the file if: - The modified timestamps changed since last time we wrote something. This is useful to know if something changed by another tool or manually without diffing the full file. - The contents changed. * further simplify checks Turns out that reading files and comparing them is fairly fast and there is no huge benefit over only using the Stats of the file and keeping track of that information. Thanks @kentcdodds! Co-authored-by: Robin Malfait --- src/cli.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/cli.js b/src/cli.js index daaea3150ca5..817aa10259a8 100644 --- a/src/cli.js +++ b/src/cli.js @@ -41,6 +41,15 @@ function formatNodes(root) { } } +async function outputFile(file, contents) { + if (fs.existsSync(file) && (await fs.promises.readFile(file, 'utf8')) === contents) { + return // Skip writing the file + } + + // Write the file + await fs.promises.writeFile(file, contents, 'utf8') +} + function help({ message, usage, commands, options }) { let indent = 2 @@ -534,6 +543,7 @@ async function build() { if (!output) { return process.stdout.write(result.css) } + return Promise.all( [ fs.promises.writeFile(output, result.css, () => true), @@ -664,10 +674,10 @@ async function build() { return process.stdout.write(result.css) } - await Promise.all( + return Promise.all( [ - fs.promises.writeFile(output, result.css, () => true), - result.map && fs.writeFile(output + '.map', result.map.toString(), () => true), + outputFile(output, result.css), + result.map && outputFile(output + '.map', result.map.toString()), ].filter(Boolean) ) })