Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
147 lines (126 loc) · 4.81 KB
/
Copy pathserver.js
File metadata and controls
147 lines (126 loc) · 4.81 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
const express = require('express');
const cors = require('cors');
const multer = require('multer');
const { execFile } = require('child_process');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// Request Logging Middleware
app.use((req, res, next) => {
console.log(`[REQUEST] ${req.method} ${req.url}`);
next();
});
app.use(express.static(path.join(__dirname, 'public')));
// Configure Multer for temp file uploads
const upload = multer({ dest: 'temp/' });
// Ensure temp directory exists
const tempDir = path.join(__dirname, 'temp');
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir);
}
// Run the C++ engine with args and return parsed JSON
function runCompressor(args) {
return new Promise((resolve, reject) => {
const binaryPath = path.join(__dirname, 'huffman_app');
console.log(`[EXEC] Running: ${binaryPath} ${args.join(' ')}`);
execFile(binaryPath, args, { maxBuffer: 1024 * 1024 * 50 }, (error, stdout, stderr) => {
if (error) {
console.error(`[EXEC ERROR] Code execution failed: ${stderr || error.message}`);
return reject(new Error(stderr || error.message));
}
try {
const response = JSON.parse(stdout.trim());
if (response.error) {
return reject(new Error(response.error));
}
resolve(response);
} catch (e) {
reject(new Error(`Failed to parse C++ engine response: ${stdout}`));
}
});
});
}
// Compress API Endpoint
app.post('/api/compress', upload.single('file'), async (req, res) => {
let inputFilePath = '';
let outputFilePath = '';
const uniqueId = crypto.randomBytes(8).toString('hex');
try {
let inputText = '';
if (req.file) {
inputFilePath = req.file.path;
inputText = fs.readFileSync(inputFilePath, 'utf8');
} else if (req.body.text !== undefined) {
inputText = req.body.text;
inputFilePath = path.join(tempDir, `input_${uniqueId}.txt`);
fs.writeFileSync(inputFilePath, inputText, 'utf8');
} else {
return res.status(400).json({ error: 'No text or file provided.' });
}
outputFilePath = path.join(tempDir, `output_${uniqueId}.huff`);
// Execute C++ Compression
const result = await runCompressor(['-api', '-c', inputFilePath, outputFilePath]);
// Read the resulting compressed .huff file and encode as Base64
let compressedBase64 = '';
if (fs.existsSync(outputFilePath)) {
const compressedBuffer = fs.readFileSync(outputFilePath);
compressedBase64 = compressedBuffer.toString('base64');
}
res.json({
...result,
originalText: inputText,
compressedBase64
});
} catch (err) {
res.status(500).json({ error: err.message });
} finally {
// Clean up temporary files
if (inputFilePath && fs.existsSync(inputFilePath) && !req.file) {
fs.unlinkSync(inputFilePath);
}
if (req.file && fs.existsSync(req.file.path)) {
fs.unlinkSync(req.file.path);
}
if (outputFilePath && fs.existsSync(outputFilePath)) {
fs.unlinkSync(outputFilePath);
}
}
});
// Decompress API Endpoint
app.post('/api/decompress', upload.single('file'), async (req, res) => {
let inputFilePath = '';
let outputFilePath = '';
const uniqueId = crypto.randomBytes(8).toString('hex');
try {
if (req.file) {
inputFilePath = req.file.path;
} else if (req.body.compressedBase64) {
const buffer = Buffer.from(req.body.compressedBase64, 'base64');
inputFilePath = path.join(tempDir, `input_${uniqueId}.huff`);
fs.writeFileSync(inputFilePath, buffer);
} else {
return res.status(400).json({ error: 'No compressed file or data provided.' });
}
outputFilePath = path.join(tempDir, `output_${uniqueId}.txt`);
// Execute C++ Decompression
const result = await runCompressor(['-api', '-d', inputFilePath, outputFilePath]);
res.json(result);
} catch (err) {
res.status(500).json({ error: err.message });
} finally {
// Clean up temporary files
if (inputFilePath && fs.existsSync(inputFilePath)) {
fs.unlinkSync(inputFilePath);
}
if (outputFilePath && fs.existsSync(outputFilePath)) {
fs.unlinkSync(outputFilePath);
}
}
});
app.listen(PORT, () => {
console.log(`[SERVER] REST API Wrapper running on http://localhost:${PORT}`);
});