1
+ const CSVFile = require ( '../models/mongoose' ) ;
2
+ const fs = require ( 'fs' ) ;
3
+ const path = require ( 'path' ) ;
4
+ const papa = require ( 'papaparse' ) ;
5
+
6
+
7
+ //render homepage
8
+ module . exports . homePage = async ( req , res ) => {
9
+ let files = await CSVFile . find ( { } ) ;
10
+ res . render ( 'home' , {
11
+ title : 'CSV Upload | Home' ,
12
+ files : files
13
+ } ) ;
14
+
15
+ }
16
+
17
+ //create and parse CSV
18
+ module . exports . uploadFile = ( req , res ) => {
19
+
20
+ CSVFile . uploadedCSV ( req , res , async function ( err ) {
21
+ try {
22
+
23
+ let csvFile = await CSVFile . findOne ( { name :req . file . originalname } ) ;
24
+ if ( csvFile ) {
25
+ req . flash ( 'error' , 'CSV already exists! 😧' )
26
+ return res . redirect ( 'back' ) ;
27
+ }
28
+
29
+ //parsing CSV using papaparse
30
+ const CSVFileUP = req . file . path ;
31
+ const csvData = fs . readFileSync ( CSVFileUP , 'utf8' ) ;
32
+
33
+ const conversedFile = papa . parse ( csvData , {
34
+ header : false
35
+
36
+ } ) ;
37
+
38
+ //allowing only CSV input type
39
+ if ( req . file && req . file . mimetype == 'text/csv' ) {
40
+ //inserting the converted JSON to DB
41
+ let csvFile = CSVFile . create ( {
42
+ name : req . file . originalname ,
43
+ file : conversedFile . data
44
+ } ) ;
45
+ req . flash ( 'success' , 'CSV uploaded successfully 🤙' ) ;
46
+ return res . redirect ( 'back' ) ;
47
+ } else {
48
+ req . flash ( 'error' , 'only CSV file allowed' ) ;
49
+ return res . redirect ( 'back' ) ;
50
+ }
51
+
52
+
53
+ } catch ( err ) {
54
+ //cathching errors and rendering common error page in the FE along with notification
55
+ console . log ( "error" , err ) ;
56
+ req . flash ( 'error' , 'something went wrong ☹️' ) ;
57
+ return res . render ( 'servererror' ) ;
58
+
59
+
60
+ }
61
+ } )
62
+ }
63
+
64
+ //display CSV Data
65
+ module . exports . displayCSV = async ( req , res ) => {
66
+ let displayData = await CSVFile . findById ( req . params . id ) ;
67
+ return res . render ( 'table' , {
68
+ title : 'CSV Upload | Details' ,
69
+ file : displayData . name ,
70
+ keys : displayData . file [ 0 ] ,
71
+ results : displayData . file
72
+ } )
73
+ } ;
74
+
75
+ //delete CSV from DB
76
+ module . exports . deleteCSV = async ( req , res ) => {
77
+ let deleteCSV = await CSVFile . findByIdAndDelete ( req . params . id ) ;
78
+ req . flash ( 'success' , 'CSV removed successfully 🤘' ) ;
79
+ return res . redirect ( 'back' ) ;
80
+ }
0 commit comments