-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
144 lines (119 loc) · 4.28 KB
/
server.js
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
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const http = require('http');
const mongoose = require('mongoose');
const { exec } = require('child_process');
const { MongoClient, GridFSBucket, ObjectId } = require('mongodb');
const path = require('path');
const upload = multer({ dest: 'uploads/' });
const app = express();
const PORT = 3000;
const mongoURI = 'mongodb://localhost:27017';
const dbName = 'exp';
let db;
// Connect to MongoDB
async function connectToDatabase() {
const client = new MongoClient(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true });
await client.connect();
db = client.db(dbName);
}
// Serve static files
app.use(express.static('public'));
// Load the main page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'public.html'));
});
// Get list of files
app.get('/files', async (req, res) => {
try {
const files = await db.collection('fs.files').find().toArray();
res.json(files);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Failed to retrieve file list');
}
});
// Download file
app.get('/download/:id', async (req, res) => {
try {
const bucket = new GridFSBucket(db);
const file = await db.collection('fs.files').findOne({ _id: new ObjectId(req.params.id) });
if (!file) {
return res.status(404).send('File not found');
}
const downloadStream = bucket.openDownloadStream(new ObjectId(req.params.id));
// Set response headers
res.setHeader('Content-disposition', `attachment; filename="${file.filename}"`);
res.setHeader('Content-type', 'application/octet-stream');
// Pipe file stream to response
downloadStream.pipe(res);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Failed to download file');
}
});
// Upload file
app.post('/upload', upload.single('dataset'), async (req, res) => {
try {
if (!req.file) {
throw new Error('No file uploaded');
}
const bucket = new GridFSBucket(db);
const filename = req.file.originalname;
const filepath = req.file.path;
// const filedescription = req.body.filedescription;
// const fileauthor = req.body.fileauthor;
// const filedate = req.body.filedate;
// const filetags = req.body.filetags;
const uploadStream = bucket.openUploadStream(filename);
const fileStream = fs.createReadStream(filepath);
fileStream.pipe(uploadStream);
uploadStream.on('error', () => {
throw new Error('Failed to upload file');
});
uploadStream.on('finish', () => {
fs.unlinkSync(filepath);
res.sendStatus(200);
});
} catch (error) {
console.error('Error:', error);
res.status(500).send('Failed to upload file');
}
});
// Delete file
app.delete('/delete/:id', async (req, res) => {
try {
const fileId = req.params.id;
const bucket = new GridFSBucket(db);
// Find the file in the database
const file = await db.collection('fs.files').findOne({ _id: new ObjectId(fileId) });
if (!file) {
return res.status(404).send('File not found');
}
// Delete the file from the database
await bucket.delete(new ObjectId(fileId));
res.status(200).send('File deleted successfully');
} catch (error) {
console.error('Error:', error);
res.status(500).send('Failed to delete file');
}
});
// Start server
connectToDatabase().then(() => {
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
const command = process.platform === 'win32' ? 'start' : process.platform === 'darwin' ? 'open' : 'xdg-open';
exec(`${command} http://localhost:${PORT}`, (error, stdout, stderr) => {
if (error) {
console.error(`Error opening browser: ${error.message}`);
return;
}
if (stderr) {
console.error(`Error opening browser: ${stderr}`);
return;
}
console.log('Browser opened successfully');
});
});
});