-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathindex.js
More file actions
38 lines (28 loc) · 842 Bytes
/
index.js
File metadata and controls
38 lines (28 loc) · 842 Bytes
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
'use strict';
const express = require('express');
const fastcsv = require('fast-csv');
const User = require('./models/User');
// Setup Express.js app
const app = express();
// TODO: everything else
app.get('/users', async (req, res) => {
try {
const users = await User.find({}).select('name email').lean();
if (users.length > 0) {
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', 'attachment; filename=users.csv');
const csvStream = fastcsv.format({ headers: true });
csvStream.pipe(res);
users.forEach((user) => {
csvStream.write(user);
});
csvStream.end();
} else {
res.status(404).send('No data to export');
}
} catch (error) {
console.error(error);
res.status(500).send('Server Error');
}
});
app.listen(3000);