-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.cjs
More file actions
63 lines (55 loc) · 2.21 KB
/
node.cjs
File metadata and controls
63 lines (55 loc) · 2.21 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
const path = require('path');
const express = require('express');
const multer = require('multer');
const cors = require('cors');
const { convertToMarkdown } = require('./converter.cjs');
// Custom storage configuration for Multer
const storage = multer.diskStorage({
destination: 'uploads/',
filename: (req, file, cb) => {
// Extract the original file name without extension
const originalName = path.parse(file.originalname).name.replace(/\s+/g, '_');
// Get the original file extension
const extension = path.extname(file.originalname);
// Generate a unique name by adding the current date and time
const uniqueSuffix = Date.now();
// Assign the name with the original extension
const filename = `${originalName}-${uniqueSuffix}${extension}`;
cb(null, filename);
}
});
const upload = multer({ storage });
function startServer(port = 3002, retries = 5) {
return new Promise((resolve, reject) => {
const app = express();
const PORT = port;
app.use(cors());
app.use(express.static(path.join(__dirname)));
app.post('/convert', upload.single('file'), (req, res) => {
try {
const filePath = path.join(__dirname, req.file.path);
convertToMarkdown(filePath, (err, markdown) => {
if (err) {
return res.status(500).send('Error converting the file.');
}
res.send({ markdown });
});
} catch (error) {
return res.status(500).send('Error converting the file.');
}
});
const server = app.listen(PORT, () => {
// console.log(`Server running on port ${PORT}`);
resolve({ port: PORT, app, server });
});
server.on('error', (error) => {
if (error.code === 'EADDRINUSE' && retries > 0) {
console.warn(`\x1b[33m🔄 Port ${PORT} in use. Trying port ${PORT + 1}...\x1b[0m`);
startServer(PORT + 1, retries - 1).then(resolve).catch(reject);
} else {
reject(error);
}
});
});
}
module.exports = { startServer };