-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
92 lines (74 loc) · 2 KB
/
index.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
const csv1 = require('csv-parser'),
fs = require('fs'),
express = require("express"),
bodyParser = require("body-parser"),
multer = require('multer'),
app = express(),
PORT = process.env.PORT || 5000;
const data = []
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./data");
},
filename: function (req, file, callback) {
if (fs.existsSync('./data/data.csv')) {
fs.unlink('./data/data.csv', function (err) {
if (err) throw err;
// if no error, file has been deleted successfully
console.log('File deleted!');
});
}
callback(null, 'data.csv');
}
});
const upload = multer({
storage: Storage
}).array("csv", 1); //Field name and max count
const getDate = () => {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth();
const day = date.getDay();
const time = date.getHours() + ':' + date.getMinutes();
return `${year}-${month}-${day} ${time}`
}
app.get("/", function (req, res, next) {
res.render("index");
});
app.post("/", function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end("Something went wrong!");
}
})
data.length = 0;
try {
fs.createReadStream('./data/data.csv')
.pipe(csv1())
.on('data', (row) => {
data.push(row);
console.log(data)
})
.on('error', (error) => `Err: ${error}`)
.on('end', (row) => {
console.log('CSV file successfully processed');
res.redirect('/data.xml/');
});
} catch (e) {
console.log(e)
return next(error)
}
})
app.get("/data.xml/", function (req, res, next) {
res.type('text/xml', "utf-8");
res.render("feed", {
data: data,
date: getDate(),
});
});
app.listen(PORT);
console.log(`Listen ${PORT}`)