63 lines
2.7 KiB
JavaScript
63 lines
2.7 KiB
JavaScript
const strip = require('strip-comments');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const SUPPORTED = ['.js', '.css', '.ejs'];
|
|
|
|
function cleanContent(content, ext) {
|
|
if (!SUPPORTED.includes(ext)) return content;
|
|
if (ext === '.ejs') content = content.replace(/<%#.*?%>/gs, '');
|
|
return strip(content, { preserveNewlines: true });
|
|
}
|
|
|
|
function processFile(inputPath, outputPath = null) {
|
|
const ext = path.extname(inputPath).toLowerCase();
|
|
if (!SUPPORTED.includes(ext)) return { skipped: inputPath };
|
|
const content = fs.readFileSync(inputPath, 'utf8');
|
|
const cleaned = cleanContent(content, ext);
|
|
const target = outputPath || inputPath;
|
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
fs.writeFileSync(target, cleaned, 'utf8');
|
|
return { ok: inputPath };
|
|
}
|
|
|
|
function processDirectory(inputDir, outputDir = null) {
|
|
const results = { processed: [], skipped: [], errors: [] };
|
|
function walk(dir, outBase) {
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
const inPath = path.join(dir, entry.name);
|
|
const outPath = outBase ? path.join(outBase, path.relative(inputDir, inPath)) : null;
|
|
if (entry.isDirectory()) {
|
|
walk(inPath, outBase ? path.dirname(outPath) : null);
|
|
} else {
|
|
const ext = path.extname(entry.name).toLowerCase();
|
|
if (SUPPORTED.includes(ext)) {
|
|
try { processFile(inPath, outPath); results.processed.push(entry.name); }
|
|
catch (e) { results.errors.push(`${entry.name}: ${e.message}`); }
|
|
} else { results.skipped.push(entry.name); }
|
|
}
|
|
}
|
|
}
|
|
walk(inputDir, outputDir);
|
|
return results;
|
|
}
|
|
|
|
if (require.main === module) {
|
|
const [,, cmd, input, output] = process.argv;
|
|
if (cmd === 'file' && input) {
|
|
const res = processFile(input, output || null);
|
|
if (res.ok) console.log(`[OK] ${path.basename(input)}`);
|
|
else if (res.skipped) console.log(`[SKIP] ${path.basename(input)}`);
|
|
process.exit(0);
|
|
}
|
|
if (cmd === 'dir' && input) {
|
|
const res = processDirectory(input, output || null);
|
|
console.log(`✅ Обработано: ${res.processed.length}`);
|
|
if (res.skipped.length) console.log(`⊘ Пропущено: ${res.skipped.length}`);
|
|
if (res.errors.length) console.error(`❌ Ошибки: ${res.errors.join(', ')}`);
|
|
process.exit(res.errors.length ? 1 : 0);
|
|
}
|
|
console.log('Использование:\n node cleaner.js file <input> [output]\n node cleaner.js dir <inputDir> [outputDir]');
|
|
process.exit(1);
|
|
}
|
|
module.exports = { cleanContent, processFile, processDirectory, SUPPORTED };
|