-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
67 lines (57 loc) · 1.8 KB
/
server.js
File metadata and controls
67 lines (57 loc) · 1.8 KB
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
var express = require('express');
var app = express();
var fs = require('fs');
var hbs = require('hbs');
var path = require('path');
var bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
// set the view engine to use handlebars
app.set('views', __dirname + '/views');
app.set('view engine', '.hbs');
//display the landing page (search form)
app.get('/', function (req, res) {
res.sendFile( __dirname + "/public/" + "index.html" );
});
//save the movie title when they click the favorite button
app.get('/save-favorites', function (req, res) {
//read stored data
var data = fs.readFileSync('./data.json');
var dataJSON = JSON.parse(data);
//append new favorite
dataJSON.favorites.push(req.query.title);
var newFavorites = remove_duplicates_safe(dataJSON.favorites);
// Prepare output in JSON format
response = {
favorites:newFavorites,
};
//saves data to data.json file
fs.writeFile('data.json', JSON.stringify(response), function (err,data) {
if (err) {
return console.log(err);
}
});
//redirect to favorites page
res.redirect("/favorites");
});
//lists all the favorites
app.get('/favorites', function(req, res) {
var data = fs.readFileSync('./data.json');
res.render('favorites', JSON.parse(data));
});
app.listen(process.env.PORT || 3000, function() {
console.log("Listening on port 3000");
});
//function to remove duplicates in an array
function remove_duplicates_safe(arr) {
var obj = {};
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
if (!(arr[i] in obj)) {
arr2.push(arr[i]);
obj[arr[i]] = true;
}
}
return arr2;
}