From c1b86ddcffbbb3f655a6ad460d34ed5552cff1bc Mon Sep 17 00:00:00 2001 From: Imran Imtiaz Date: Tue, 19 Aug 2025 08:16:14 +0400 Subject: [PATCH] Update index.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I converted the script from a callback-based approach to one that uses fs/promises with async/await, which makes the code cleaner and easier to read. Instead of appending CSS files one by one using fs.appendFile—which can cause race conditions because file reads happen asynchronously—I updated the logic so that all CSS files are read first, combined into a single string using join("\n"), and then written to bundle.css in one go. This ensures the output is always consistent and avoids partial or out-of-order writes. I also added a step to automatically create the output directory with fs.mkdir(..., { recursive: true }) so the script will not fail if project-dist does not already exist. The file order is preserved based on how readdir returns them, but the code can easily be extended to sort alphabetically if needed. Finally, I wrapped the entire process in a try/catch block with a clear log message on success, which makes the script more robust and user-friendly. --- 05-merge-styles/index.js | 55 +++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 29 deletions(-) diff --git a/05-merge-styles/index.js b/05-merge-styles/index.js index 7cb46c53..7c668674 100644 --- a/05-merge-styles/index.js +++ b/05-merge-styles/index.js @@ -1,34 +1,31 @@ -const fs = require('fs'); -const path = require('path'); -let fileDirection = path.resolve(__dirname + '/project-dist/bundle.css'); +const fs = require("fs/promises"); +const path = require("path"); -fs.writeFile( - fileDirection, - '', - (err) => { - if (err) throw err; - }); +const stylesDir = path.join(__dirname, "05-merge-styles", "styles"); +const bundlePath = path.join(__dirname, "project-dist", "bundle.css"); -fs.readdir('05-merge-styles/styles', {withFileTypes: true}, function(err, items) { - let res = []; - for (let i = 0; i { - - res.push(data); +async function mergeStyles() { + try { + // Ensure output directory exists + await fs.mkdir(path.dirname(bundlePath), { recursive: true }); - fs.appendFile( - fileDirection, - data, - err => { - if (err) throw err; - }); - - }); - } - - } - -}); + // Get all style files + const items = await fs.readdir(stylesDir, { withFileTypes: true }); + const cssFiles = items + .filter(item => item.isFile() && path.extname(item.name) === ".css") + .map(item => path.join(stylesDir, item.name)); + + // Read all CSS files in order + const contents = await Promise.all( + cssFiles.map(file => fs.readFile(file, "utf-8")) + ); + // Write them into one file + await fs.writeFile(bundlePath, contents.join("\n")); + console.log("CSS merged successfully into bundle.css"); + } catch (err) { + console.error("Error merging CSS:", err); + } +} +mergeStyles();