uglify-js-minify-css-allfiles 1.3.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ {
2
+ "cSpell.words": [
3
+ "allfile",
4
+ "allfiles",
5
+ "comporessor",
6
+ "corejs",
7
+ "esmodules",
8
+ "minifycss",
9
+ "oinochoe",
10
+ "uglifyjs",
11
+ "yeongmin"
12
+ ]
13
+ }
package/CHANGELOG.md CHANGED
@@ -1,19 +1,85 @@
1
1
  # Changelog
2
2
 
3
- ## v 1.3.2 (2023-05-28)
4
-
5
- - feature: [Add new `CHANGELOG.md`](/CHANGELOG.md)
6
- - fix & etc:
7
- - fix
8
- - bug fixed(1.1.7) - Solved cleancss first line delete error. - 2020/08/21
9
- - bug fixed(1.1.3) - ... 2020/08/15
10
- - etc
11
- - When CSS Warnings is exist, not minify any code. - 2022/04/13
12
- - UglifyJS Updated removing 'console.info, console.warn, console.error'. - 2021/11/12
13
- - UglifyJS Updated working without 'console.log' not console.error, info etc. - 2021/03/17
14
- - UglifyJS Updated and you can uglify JavaScript files even ES6 sentences! - 2020/11/03
15
- - Moving DevDependencies to Dependencies for this production. - 2020/08/26
16
- - Solved cleancss commentary issue because of changed CSS options. - 2020/08/21
17
- - Add command line execution with 2 parameters.
18
- - Add the exceptFolder parameter. - 2020/08/20
19
- - You can use relative path.
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [2.0.0] - 2024-08-19
9
+
10
+ ### Added
11
+
12
+ - New logging system for better error tracking and debugging
13
+ - Optional Babel integration for advanced JavaScript transpilation
14
+ - Support for ES modules, allowing use of `import` statements in your projects
15
+
16
+ ### Changed
17
+
18
+ - Switched from CommonJS (`require`) to ES modules (`import`) for better compatibility with modern JavaScript
19
+ - Improved error handling and reporting, providing clearer messages for troubleshooting
20
+ - Enhanced CLI interface with more user-friendly options and feedback
21
+
22
+ ### Improved
23
+
24
+ - Significantly faster processing of large directories with many files
25
+ - More robust handling of different file types and encodings
26
+ - Better preservation of source maps in minified files
27
+
28
+ ### Breaking Changes
29
+
30
+ - Minimum Node.js version requirement increased to v14.0.0
31
+ - Configuration file format changed (see migration guide for details)
32
+ - Some CLI options have been renamed for clarity (see documentation for new option names)
33
+
34
+ ## [1.3.2] - 2023-05-28
35
+
36
+ ### Added
37
+
38
+ - New `CHANGELOG.md` file
39
+
40
+ ### Changed
41
+
42
+ - When CSS warnings exist, no code is minified (2022-04-13)
43
+ - Updated UglifyJS to remove 'console.info, console.warn, console.error' (2021-11-12)
44
+ - Updated UglifyJS to work without 'console.log' but keep console.error, info, etc. (2021-03-17)
45
+
46
+ ### Fixed
47
+
48
+ - Bug fix (v1.1.7): Solved CleanCSS first line delete error (2020-08-21)
49
+ - Bug fix (v1.1.3): [Description missing] (2020-08-15)
50
+
51
+ ## [1.3.1] - 2020-11-03
52
+
53
+ ### Changed
54
+
55
+ - Updated UglifyJS to support minification of JavaScript files with ES6 syntax
56
+
57
+ ## [1.3.0] - 2020-08-26
58
+
59
+ ### Changed
60
+
61
+ - Moved DevDependencies to Dependencies for production use
62
+
63
+ ## [1.2.0] - 2020-08-21
64
+
65
+ ### Fixed
66
+
67
+ - Solved CleanCSS commentary issue due to changed CSS options
68
+
69
+ ### Added
70
+
71
+ - Support for command line execution with 2 parameters
72
+
73
+ ## [1.1.0] - 2020-08-20
74
+
75
+ ### Added
76
+
77
+ - New `exceptFolder` parameter to exclude specific folders from minification
78
+ - Support for using relative paths
79
+
80
+ [2.0.0]: https://github.com/oinochoe/uglify-js-minify-css-allfiles/compare/v1.3.2...v2.0.0
81
+ [1.3.2]: https://github.com/oinochoe/uglify-js-minify-css-allfiles/compare/v1.3.1...v1.3.2
82
+ [1.3.1]: https://github.com/oinochoe/uglify-js-minify-css-allfiles/compare/v1.3.0...v1.3.1
83
+ [1.3.0]: https://github.com/oinochoe/uglify-js-minify-css-allfiles/compare/v1.2.0...v1.3.0
84
+ [1.2.0]: https://github.com/oinochoe/uglify-js-minify-css-allfiles/compare/v1.1.0...v1.2.0
85
+ [1.1.0]: https://github.com/oinochoe/uglify-js-minify-css-allfiles/compare/releases/tag/v1.1.0
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2020 NOEL <copstyle86@gmail.com>
3
+ Copyright (c) 2024 NOEL <copstyle86@gmail.com>
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
18
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
21
+ SOFTWARE.
package/README.md CHANGED
@@ -13,7 +13,9 @@
13
13
 
14
14
  # uglify-js-minify-css-allfiles
15
15
 
16
- uglify-js-minify-css-allfiles helps hide the code you don't want to see, obfuscate the code in the deployment environment through a simple CLI in the build environment, and make it less recognizable to others. you can do this easily via `demo.js` file in `node_modules/uglify-js-minify-css-allfiles`. you are able to minify all files in a specific folder.
16
+ A powerful tool to minify and obfuscate JavaScript and CSS files in your project.
17
+ It helps protect your code in deployment environments and makes it less recognizable to others, all through a simple CLI interface.
18
+ You can easily minify all files in a specific folder, with the option to exclude certain directories.
17
19
 
18
20
  [![NPM](https://nodei.co/npm/uglify-js-minify-css-allfiles.png?downloads=true&stars=true)](https://www.npmjs.com/package/uglify-js-minify-css-allfiles)
19
21
 
@@ -22,11 +24,11 @@ uglify-js-minify-css-allfiles helps hide the code you don't want to see, obfusca
22
24
  ## Table of Contents
23
25
 
24
26
  - [Installation](#installation)
25
- - [Examples](#examples)
27
+ - [Usage](#usage)
28
+ - [Parameters](#parameters)
29
+ - [BabelOptions](#babeloptions)
26
30
  - [Changelog](#changelog)
27
31
  - [License](#license)
28
- <!-- - [API](#api)
29
- - [`Methods`](#methods) -->
30
32
 
31
33
  ## Installation
32
34
 
@@ -36,43 +38,66 @@ Install with `npm`:
36
38
  $ npm i uglify-js-minify-css-allfiles
37
39
  ```
38
40
 
39
- ## Examples
41
+ ## Usage
40
42
 
41
- ```js
42
- // index.js
43
- const minifyAll = require('uglify-js-minify-css-allfiles');
43
+ 1. Basic usage (no Babel):
44
44
 
45
- /**
46
- * @param1 - Type the folder name you want to change all files inside.
47
- * @param2 - Type the folder name you never want to change all files inside.
48
- * @functions - minifyAll(minifyFolder, noMinifyFolder)
49
- */
45
+ ```js
46
+ import minifyAll from 'uglify-js-minify-css-allfiles';
50
47
 
51
- // Example 1
52
- minifyAll('../test/', 'lib');
48
+ await minifyAll('./src/', 'node_modules');
49
+ ```
53
50
 
54
- // Example 2
55
- minifyAll(process.argv.slice(2)[0], process.argv.slice(2)[1]);
56
- ```
51
+ 2. Using Babel with default settings:
57
52
 
58
- <!--
59
- ## API
53
+ ```js
54
+ import minifyAll from 'uglify-js-minify-css-allfiles';
60
55
 
61
- ### `Methods`
56
+ await minifyAll('./src/', 'node_modules', { useBabel: true });
57
+ ```
62
58
 
63
- Create a new progress bar. It's necessary to wait for the [`ready` event](https://github.com/electron/electron/blob/master/docs/api/app.md#event-ready) to be emitted by [Electron's BrowserWindow](https://github.com/electron/electron/blob/master/docs/api/browser-window.md), since the progress bar is displayed within it. Optionally, you can pass the electron app as a second parameter (parameter `electronApp`) when creating the progress bar. Check the sample code on this page for detailed examples on how to set properties to `options`.
59
+ 3. Using custom Babel presets:
64
60
 
65
- You can define most of the characteristics of the progress bar using the `options` parameter. Below is a list of properties that you can set for the `options` parameter.
61
+ ```js
62
+ import minifyAll from 'uglify-js-minify-css-allfiles';
66
63
 
67
- | Option name | Type | Default value | Description |
68
- | ------------ | -------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
69
- | debug | <code>boolean</code> | <code>false</code> | Specifies whether debugging should be enabled. If set to `true`, the browser's DevTools panel will automatically open when the progress bar is created. This can be helpful when debugging and/or dealing with issues. |
70
- | abortOnError | <code>boolean</code> | <code>false</code> | Specifies whether the progress bar should automatically abort and close if an error occurs internally. | -->
64
+ await minifyAll('./src/', 'node_modules', {
65
+ presets: [
66
+ [
67
+ '@babel/preset-env',
68
+ {
69
+ targets: {
70
+ esmodules: false, // Target ES2015
71
+ },
72
+ },
73
+ ],
74
+ ],
75
+ });
76
+ ```
71
77
 
72
- ---
78
+ ## Parameters
79
+
80
+ The `minifyAll` function accepts the following parameters:
81
+
82
+ | Parameter | Type | Default | Description |
83
+ | --------------- | -------------- | ------- | -------------------------------------------------------------------------------------------- |
84
+ | `contentPath` | string | - | The path to the directory containing the files to be minified. This is a required parameter. |
85
+ | `excludeFolder` | string | `''` | The name of a folder to exclude from minification. Leave empty to include all folders. |
86
+ | `babelOptions` | object or null | `null` | An object containing Babel options or a flag to use default Babel settings. |
87
+
88
+ ## BabelOptions
89
+
90
+ The `babelOptions` parameter can have the following properties:
91
+
92
+ | Property | Type | Default | Description |
93
+ | ---------- | ------- | ------- | --------------------------------------------------------------------------------------------- |
94
+ | `useBabel` | boolean | `false` | If set to `true`, enables Babel transformation with default presets targeting ES2015. |
95
+ | `presets` | array | - | Custom Babel presets to use for transformation. If provided, overrides the `useBabel` option. |
73
96
 
74
97
  ## Changelog
75
98
 
99
+ See CHANGELOG.md for details on each release.
100
+
76
101
  [Changelog](/CHANGELOG.md)
77
102
 
78
103
  ## License
package/demo.js CHANGED
@@ -1,4 +1,18 @@
1
- const minifyAll = require('./minify.js');
2
- minifyAll('./test/lib');
1
+ import minifyAll from './dist/module.js';
2
+
3
+ minifyAll('./test/', 'lib', { useBabel: true });
4
+
5
+ // minifyAll('./test/', 'lib', {
6
+ // presets: [
7
+ // [
8
+ // '@babel/preset-env',
9
+ // {
10
+ // targets: {
11
+ // esmodules: false, // Target ES2015
12
+ // },
13
+ // },
14
+ // ],
15
+ // ],
16
+ // });
3
17
  // console.log(process.argv.slice(2)[0], process.argv.slice(2)[1]);
4
18
  // minifyAll(process.argv.slice(2)[0], process.argv.slice(2)[1]);
package/dist/module.js CHANGED
@@ -1,89 +1,139 @@
1
1
  /**
2
- * uglify-js and minify-css allFiles
2
+ * uglify-js and minify-css for all files
3
3
  * Released under the terms of MIT license
4
4
  *
5
- * Copyright (C) 2020 yeongmin
5
+ * Copyright (C) 2024 yeongmin
6
6
  */
7
7
 
8
- const fs = require('fs');
9
- const path = require('path');
10
- const uglifyJS = require('uglify-js');
11
- const cleanCSS = require('clean-css');
12
- const DIRECTORY = {
13
- JAVASCRIPT: '.js',
14
- STYLESHEET: '.css',
15
- };
16
- const CSSOPTIONS = {
17
- level: { 1: { all: false } },
18
- };
19
- let errorFilesNumber = 0;
20
- let errorFileObjects = [];
8
+ import { promises as fs } from 'fs';
9
+ import path from 'path';
10
+ import Logger from './modules/logger.js';
11
+ import { getAllFiles, writeFile } from './modules/fileHandler.js';
12
+ import { minifyJS, minifyCSS } from './modules/minifier.js';
13
+ import babelCore from '@babel/core';
21
14
 
22
- // getFiles..
23
- const getAllFiles = (pathDir, callback) => {
24
- let files = fs.readdirSync(pathDir) || [];
25
- files.forEach((name) => {
26
- let filePath = path.join(pathDir, name);
27
- let fileState = fs.statSync(filePath);
28
- if (fileState.isFile()) {
29
- callback(filePath, fileState);
30
- } else if (fileState.isDirectory()) {
31
- getAllFiles(filePath, callback);
32
- }
33
- });
34
- };
15
+ const FILE_HANDLERS = {
16
+ '.js': async (filePath, content, logger, babelOptions) => {
17
+ try {
18
+ // Transform the code using Babel with preset-env
19
+ let transformed = content;
35
20
 
36
- // minify All Files..
37
- module.exports = async function minifyAll(contentsPath, exceptFolder) {
38
- let CONTENTSDIR = contentsPath || '';
39
- let EXCEPTIONFOLDER = exceptFolder || '';
40
- let result = '';
41
- getAllFiles(CONTENTSDIR, (paths) => {
42
- let code = fs.readFileSync(paths, 'utf-8');
43
- if (EXCEPTIONFOLDER !== '' && paths.includes(EXCEPTIONFOLDER)) return;
44
- if (paths.substr(-3) === DIRECTORY.JAVASCRIPT) {
45
- result = uglifyJS.minify(code, {
46
- compress: {
47
- pure_funcs: ['console.log', 'console.error', 'console.warn', 'console.info'],
48
- },
49
- }).code;
50
- writeFiles(paths, result);
51
- } else if (paths.substr(-4) === DIRECTORY.STYLESHEET) {
52
- new cleanCSS(CSSOPTIONS).minify(code, function (error, output) {
53
- if (0 < output.warnings.length) {
54
- console.error('CSS FILE ERROR!', output.warnings);
55
- writeFiles(paths, null);
56
- return;
57
- } else {
58
- result = new cleanCSS(CSSOPTIONS).minify(code).styles;
59
- writeFiles(paths, result);
60
- }
61
- });
62
- }
63
- });
21
+ // Convert code to Babel when Babel option is provided
22
+ if (babelOptions) {
23
+ transformed = babelCore.transformSync(content, babelOptions).code;
24
+ }
64
25
 
65
- // writeFiles..
66
- function writeFiles(file, value) {
67
- // exception..
68
- if (typeof value == 'undefined' || value === '' || value === null) {
69
- console.error(
70
- '************error file ㅜㅜㅜㅜ***********\n' +
71
- file +
72
- '\n **********ㅗㅗㅗㅗㅗ error file********',
73
- );
74
- errorFilesNumber += 1;
75
- errorFileObjects.push(file);
76
- return;
26
+ const result = minifyJS(transformed);
27
+ await writeFile(filePath, result, logger);
28
+ } catch (error) {
29
+ await logger.logError(filePath, `Babel transformation failed: ${error.message}`);
30
+ }
31
+ },
32
+ '.css': async (filePath, content, logger) => {
33
+ const output = await minifyCSS(content);
34
+ if (output.warnings.length > 0) {
35
+ await logger.logError(filePath, `CSS warnings: ${output.warnings.join(', ')}`);
36
+ await writeFile(filePath, null, logger);
77
37
  } else {
78
- console.info(file);
79
- fs.writeFile(file, value, 'utf-8', function (error) {
80
- if (error) return console.error(error);
81
- });
38
+ await writeFile(filePath, output.styles, logger);
82
39
  }
40
+ },
41
+ };
42
+
43
+ /**
44
+ * Processes a single file based on its extension.
45
+ * @async
46
+ * @param {string} filePath - The path of the file to process.
47
+ * @param {Logger} logger - The logger instance.
48
+ * @param {Object} [babelOptions=null] - Babel options for converting JavaScript files.
49
+ * @returns {Promise<void>}
50
+ */
51
+ async function processFile(filePath, logger, babelOptions = null) {
52
+ const fileContent = await fs.readFile(filePath, 'utf-8');
53
+ const fileExtension = path.extname(filePath);
54
+ const handler = FILE_HANDLERS[fileExtension];
55
+
56
+ if (handler) {
57
+ await handler(filePath, fileContent, logger, babelOptions);
58
+ } else {
59
+ logger.logInfo(`지원되지 않는 파일 형식 건너뜀: ${filePath}`);
83
60
  }
61
+ }
62
+
63
+ /**
64
+ * Resolves Babel options based on the provided configuration.
65
+ *
66
+ * @param {Object|null} options - The Babel options object or null.
67
+ * @returns {Object|null} The resolved Babel options or null if no valid options are provided.
68
+ */
69
+ function resolveBabelOptions(options) {
70
+ if (!options) return null;
84
71
 
85
- if (0 < errorFileObjects.length) {
86
- console.info('file change ended... \nerrorFilesNumber : ' + errorFilesNumber);
87
- console.info('*******errorFileObjects******* : ' + errorFileObjects);
72
+ if (options.useBabel) {
73
+ return {
74
+ presets: [
75
+ [
76
+ '@babel/preset-env',
77
+ {
78
+ targets: {
79
+ esmodules: false, // Target ES2015
80
+ },
81
+ },
82
+ ],
83
+ ],
84
+ };
88
85
  }
89
- };
86
+
87
+ return options.presets ? options : null;
88
+ }
89
+
90
+ /**
91
+ * Minifies all JavaScript and CSS files in the specified directory and its subdirectories.
92
+ *
93
+ * @async
94
+ * @function minifyAll
95
+ * @param {string} contentPath - The path to the directory containing the files to be minified.
96
+ * @param {string} [excludeFolder=''] - The name of a folder to exclude from minification.
97
+ * @param {Object} [babelOptions=null] - Babel options for converting JavaScript files.
98
+ * @returns {Promise<void>} A promise that resolves when all files have been processed.
99
+ * @throws {Error} If there's an issue reading or writing files.
100
+ *
101
+ * @example
102
+ * // Minify all files in './test/' directory, excluding 'lib' folder
103
+ * import minifyAll from './main.js';
104
+ * await minifyAll('./test/', 'lib');
105
+ *
106
+ * @example
107
+ * // Minify all files in a directory specified as a command line argument
108
+ * import minifyAll from './main.js';
109
+ * await minifyAll(process.argv[2], process.argv[3]);
110
+ *
111
+ * @example
112
+ * // Add babel options for converting JavaScript files.
113
+ * minifyAll('./test/', 'lib', {
114
+ * presets: [
115
+ * [
116
+ * '@babel/preset-env',
117
+ * {
118
+ * targets: {
119
+ * esmodules: false, // Target ES2015
120
+ * },
121
+ * },
122
+ * ],
123
+ * ],
124
+ * });
125
+ */
126
+ export default async function minifyAll(contentPath, excludeFolder = '', babelOptions = null) {
127
+ const logger = new Logger();
128
+ await logger.initialize();
129
+
130
+ const rootDir = contentPath || '';
131
+ const finalBabelOptions = resolveBabelOptions(babelOptions);
132
+
133
+ await getAllFiles(rootDir, async (filePath) => {
134
+ if (excludeFolder && filePath.includes(excludeFolder)) return;
135
+ await processFile(filePath, logger, finalBabelOptions);
136
+ });
137
+
138
+ await logger.summarize();
139
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * File handling module for minification process.
3
+ * @module fileHandler
4
+ */
5
+
6
+ import { promises as fs } from 'fs';
7
+ import path from 'path';
8
+
9
+ /**
10
+ * Recursively gets all files in a directory and its subdirectories.
11
+ *
12
+ * @async
13
+ * @param {string} dirPath - The path to the directory to search.
14
+ * @param {Function} callback - The callback function to execute for each file.
15
+ * @returns {Promise<void>}
16
+ */
17
+ export async function getAllFiles(dirPath, callback) {
18
+ const files = await fs.readdir(dirPath);
19
+ for (const file of files) {
20
+ const filePath = path.join(dirPath, file);
21
+ const fileStat = await fs.stat(filePath);
22
+ if (fileStat.isFile()) {
23
+ await callback(filePath, fileStat);
24
+ } else if (fileStat.isDirectory()) {
25
+ await getAllFiles(filePath, callback);
26
+ }
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Writes content to a file.
32
+ *
33
+ * @async
34
+ * @param {string} filePath - The path of the file to write.
35
+ * @param {string} content - The content to write to the file.
36
+ * @param {Object} logger - The logger object for logging operations.
37
+ * @returns {Promise<void>}
38
+ */
39
+ export async function writeFile(filePath, content, logger) {
40
+ if (typeof content === 'undefined' || content === '' || content === null) {
41
+ await logger.logError(filePath, 'Invalid or empty content');
42
+ return;
43
+ }
44
+
45
+ logger.logInfo(`Writing file: ${filePath}`);
46
+ try {
47
+ await fs.writeFile(filePath, content, 'utf-8');
48
+ } catch (error) {
49
+ await logger.logError(filePath, `Write failed: ${error.message}`);
50
+ }
51
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Logger module for handling log operations.
3
+ * @module logger
4
+ */
5
+
6
+ import fs from 'fs/promises';
7
+ import path from 'path';
8
+
9
+ /**
10
+ * Get current formatted time string
11
+ * @returns {string} Formatted time string
12
+ */
13
+ function getCurrentTime() {
14
+ const now = new Date();
15
+ return now.toLocaleString('en-US', {
16
+ year: 'numeric',
17
+ month: '2-digit',
18
+ day: '2-digit',
19
+ hour: '2-digit',
20
+ minute: '2-digit',
21
+ second: '2-digit',
22
+ hour12: false,
23
+ });
24
+ }
25
+
26
+ /**
27
+ * Logger class for handling log operations.
28
+ * @class
29
+ */
30
+ class Logger {
31
+ /**
32
+ * Create a Logger instance.
33
+ * @param {string} [logDir='logs'] - The directory to store log files.
34
+ */
35
+ constructor(logDir = 'logs') {
36
+ this.logDir = logDir;
37
+ this.errorCount = 0;
38
+ this.errorFiles = [];
39
+ }
40
+
41
+ /**
42
+ * Initialize the logger by creating the log directory.
43
+ * @async
44
+ * @returns {Promise<void>}
45
+ */
46
+ async initialize() {
47
+ try {
48
+ await fs.mkdir(this.logDir, { recursive: true });
49
+ } catch (error) {
50
+ console.error(`Failed to create log directory: ${error.message}`);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Log an error message and write it to the error log file.
56
+ * @async
57
+ * @param {string} filePath - The path of the file where the error occurred.
58
+ * @param {string} reason - The reason for the error.
59
+ * @returns {Promise<void>}
60
+ */
61
+ async logError(filePath, reason) {
62
+ const logMessage = `
63
+ =============== File Error ===============
64
+ Time: ${getCurrentTime()}
65
+ File: ${filePath}
66
+ Reason: ${reason}
67
+ ==========================================
68
+ `;
69
+
70
+ console.error(logMessage);
71
+ this.errorCount++;
72
+ this.errorFiles.push(filePath);
73
+
74
+ try {
75
+ await fs.appendFile(path.join(this.logDir, 'error.log'), logMessage);
76
+ } catch (error) {
77
+ console.error(`Failed to write to error log: ${error.message}`);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Log an informational message to the console.
83
+ * @param {string} message - The message to log.
84
+ */
85
+ logInfo(message) {
86
+ console.info(`[${getCurrentTime()}] ${message}`);
87
+ }
88
+
89
+ /**
90
+ * Generate and log a summary of the processing results.
91
+ * @async
92
+ * @returns {Promise<void>}
93
+ */
94
+ async summarize() {
95
+ const summary = `
96
+ =============== Processing Summary ===============
97
+ Time: ${getCurrentTime()}
98
+ Total files processed: ${this.errorCount + this.errorFiles.length}
99
+ Files with errors: ${this.errorCount}
100
+ Error files:
101
+ ${this.errorFiles.map((file, index) => ` ${index + 1}. ${file}`).join('\n')}
102
+ ==================================================
103
+ `;
104
+
105
+ console.info(summary);
106
+
107
+ try {
108
+ await fs.appendFile(path.join(this.logDir, 'summary.log'), summary);
109
+ } catch (error) {
110
+ console.error(`Failed to write to summary log: ${error.message}`);
111
+ }
112
+ }
113
+ }
114
+
115
+ export default Logger;