-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
108 lines (92 loc) · 2.83 KB
/
app.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
var express = require('express');
var mongoose = require('mongoose');
var multer = require('multer');
var path = require('path');
var csvModel = require('./models/csv');
var csv = require('csvtojson');
var bodyParser = require('body-parser');
var storage = multer.diskStorage({
destination:(req,file,cb)=>{
cb(null,'./public/uploads');
},
filename:(req,file,cb)=>{
cb(null,file.originalname);
}
});
var uploads = multer({storage:storage});
//connect to db
mongoose.connect('mongodb+srv://Bhuvaneshwari16:Assignment@cluster3.hknhiay.mongodb.net/?retryWrites=true&w=majority',{useNewUrlParser:true})
.then(()=>console.log('connected to db'))
.catch((err)=>console.log(err))
//init app
var app = express();
//set the template engine
app.set('view engine','ejs');
//fetch data from the request
app.use(bodyParser.urlencoded({extended:false}));
//static folder
app.use(express.static(path.resolve(__dirname,'public')));
//default pageload
app.get('/',(req,res)=>{
let searchcode = req.query.search;
var query ='';
if(searchcode && !isNaN(searchcode)){
query = {$or:[{"sku_code":searchcode},{"product_name": searchcode},{"product_description":searchcode}]};
} else {
query = {$or:[{"product_name": searchcode},{"product_description":searchcode}]};
}
if(searchcode) {
csvModel.find(query, function(err, result) {
if (err) throw err;
res.render('demo',{data:result});
});
} else {
csvModel.find((err,data)=>{
if(err){
console.log(err);
}else{
if(data!=''){
res.render('demo',{data:data});
}else{
res.render('demo',{data:''});
}
}
});
}
});
var temp ;
app.post('/',uploads.single('csv'),(req,res)=>{
//Validate file is csv
let file = req.file;
if (!file.mimetype == "text/csv") {
res.send('Only .csv format allowed!');
}
//convert csvfile to jsonArray
csv()
.fromFile(req.file.path)
.then((jsonObj)=>{
console.log(jsonObj);
// for(var x=0;x<jsonObj;x++){
// temp = parseFloat(jsonObj[x].Test1)
// jsonObj[x].Test1 = temp;
// temp = parseFloat(jsonObj[x].Test2)
// jsonObj[x].Test2 = temp;
// temp = parseFloat(jsonObj[x].Test3)
// jsonObj[x].Test3 = temp;
// temp = parseFloat(jsonObj[x].Test4)
// jsonObj[x].Test4 = temp;
// temp = parseFloat(jsonObj[x].Final)
// jsonObj[x].Final = temp;
// }
csvModel.insertMany(jsonObj,(err,data)=>{
if(err){
console.log(err);
}else{
res.redirect('/');
}
});
});
});
//assign port
var port = process.env.PORT || 3000;
app.listen(port,()=>console.log('server run at port '+port));