-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
167 lines (146 loc) · 7.48 KB
/
Copy pathserver.js
File metadata and controls
167 lines (146 loc) · 7.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
const express = require('express');
const fileUpload = require('express-fileupload');
const cheerio = require('cheerio');
const beautify = require('js-beautify');
const fs = require('fs-extra');
const path = require('path');
const app = express();
const PORT = 3000;
// Ces lignes permettent à Express de lire le texte envoyé par le formulaire (le chemin)
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
// --- INTERFACE VISUELLE ---
app.get('/', (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Splitter Local</title>
<style>
body { font-family: 'Segoe UI', sans-serif; background: #f0f2f5; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
.container { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); text-align: center; max-width: 450px; width: 100%; }
h1 { color: #333; margin-bottom: 10px; font-size: 24px; }
p { color: #666; font-size: 14px; margin-bottom: 30px; }
.file-drop { border: 2px dashed #28a745; padding: 30px 20px; border-radius: 8px; background: #f4fff6; cursor: pointer; transition: 0.3s; margin-bottom: 20px; display: block; }
.file-drop:hover { background: #e8ffe0; }
input[type="file"] { display: none; }
.input-path { width: 93%; padding: 10px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 4px; font-family: inherit; }
.btn { background: #28a745; color: white; border: none; padding: 12px 30px; font-size: 16px; border-radius: 6px; cursor: pointer; font-weight: 600; width: 100%; transition: 0.2s; }
.btn:hover { background: #218838; }
#file-name { margin-top: 10px; font-weight: bold; color: #28a745; }
</style>
</head>
<body>
<div class="container">
<h1>Code Splitter Local 📁</h1>
<p>Glisse ton fichier all-in-one et indique où l'extraire.</p>
<form action="/upload" method="POST" enctype="multipart/form-data">
<label class="file-drop">
<span id="label-text">📂 Cliquer ou glisser le fichier .html</span>
<input type="file" name="htmlFile" accept=".html" required onchange="updateFileName(this)">
<div id="file-name"></div>
</label>
<input type="text" name="customPath" class="input-path" placeholder="Optionnel: C:\\chemin\\de\\destination">
<button type="submit" class="btn">Générer la structure</button>
</form>
</div>
<script>
function updateFileName(input) {
const fileName = input.files[0] ? input.files[0].name : "";
document.getElementById('file-name').textContent = fileName;
document.getElementById('label-text').textContent = "Prêt à être découpé !";
}
</script>
</body>
</html>
`);
});
// --- LOGIQUE DE TRAITEMENT ---
app.post('/upload', async (req, res) => {
if (!req.files || !req.files.htmlFile) {
return res.status(400).send('Aucun fichier reçu.');
}
try {
const file = req.files.htmlFile;
const rawHtml = file.data.toString('utf8');
const $ = cheerio.load(rawHtml);
// Récupération du chemin utilisateur ou dossier par défaut
const userPath = req.body.customPath ? req.body.customPath.trim() : __dirname;
const folderName = `${path.parse(file.name).name}_structure`;
const outputDir = path.join(userPath, folderName);
// Initialisation des dossiers
await fs.emptyDir(outputDir);
await fs.ensureDir(path.join(outputDir, 'css'));
await fs.ensureDir(path.join(outputDir, 'js'));
await fs.ensureDir(path.join(outputDir, 'assets'));
let extractedCss = "";
let extractedJs = "";
let assetCounter = 0;
function saveBase64Asset(base64Str) {
const matches = base64Str.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+);base64,(.+)$/);
if (!matches) return null;
const ext = matches[1].split('/')[1] || 'png';
const data = matches[2];
const fileName = `extracted_asset_${++assetCounter}.${ext}`;
const assetPath = path.join(outputDir, 'assets', fileName);
fs.writeFileSync(assetPath, Buffer.from(data, 'base64'));
return `assets/${fileName}`;
}
// 1. Découpage CSS
$('style').each((i, el) => {
let cssText = $(el).html() || "";
const base64Regex = /url\(["']?(data:image\/[^"';]+;base64,[^"'\)]+)["']?\)/g;
cssText = cssText.replace(base64Regex, (match, p1) => {
const relativePath = saveBase64Asset(p1);
return relativePath ? `url('../${relativePath}')` : match;
});
extractedCss += cssText + "\n\n";
$(el).remove();
});
// 2. Découpage JS
$('script').not('[src]').each((i, el) => {
extractedJs += ($(el).html() || "") + "\n\n";
$(el).remove();
});
// 3. Images HTML
$('img').each((i, el) => {
const src = $(el).attr('src');
if (src && src.startsWith('data:image')) {
const relativePath = saveBase64Asset(src);
if (relativePath) {
$(el).attr('src', relativePath);
}
}
});
// 4. Écriture
if (extractedCss.trim()) {
const formattedCss = beautify.css(extractedCss, { indent_size: 2 });
await fs.writeFile(path.join(outputDir, 'css', 'style.css'), formattedCss);
$('head').append(' <link rel="stylesheet" href="css/style.css">\n');
}
if (extractedJs.trim()) {
const formattedJs = beautify.js(extractedJs, { indent_size: 2 });
await fs.writeFile(path.join(outputDir, 'js', 'script.js'), formattedJs);
$('body').append(' <script src="js/script.js" defer></script>\n');
}
const cleanHtml = beautify.html($.html(), { indent_size: 2 });
await fs.writeFile(path.join(outputDir, 'index.html'), cleanHtml);
res.send(`
<div style="font-family: sans-serif; text-align: center; margin-top: 50px;">
<h2 style="color: #28a745;">🎉 Découpage réussi !</h2>
<p>Ton projet a été créé à cet emplacement :</p>
<code style="background: #eee; padding: 10px; border-radius: 5px; display: inline-block;">${outputDir}</code>
<br><br>
<a href="/" style="color: #007bff; text-decoration: none; font-weight: bold;">← Convertir un autre fichier</a>
</div>
`);
} catch (err) {
console.error(err);
res.status(500).send('Une erreur est survenue lors du traitement.');
}
});
app.listen(PORT, () => {
console.log(`\n⚡ Outil lancé ! Disponible sur http://localhost:${PORT}`);
});