forked from node-girls/express-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
64 lines (46 loc) · 1.54 KB
/
server.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
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
//NEW THINGS
var mustacheExpress = require('mustache-express');
///
var app = express()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
// NEW THINGS
// Register '.mustache' extension with The Mustache Express
app.engine('mustache', mustacheExpress());
app.set('view engine', 'mustache');
app.set('views', __dirname + '/views');
/////
app.post("/create-post",function(req,res){
res.redirect('/');
var myFile=__dirname+'/data/posts.json';
fs.readFile(myFile,function(error,file){
var parsedFile = JSON.parse(file);
parsedFile[Date.now()] = req.body;
// console.log(parsedFile);
var JSONText = JSON.stringify(parsedFile);
fs.writeFile(myFile,JSONText,function(error){
// console.log("imhere");
})
});
});
app.get('/get-posts', function(req,res){
res.sendFile(__dirname+'/data/posts.json');
});
//NEW THINGS
app.get('/posts/:postId', function(req,res){
// var blogpost;
fs.readFile(__dirname+'/data/posts.json',function(error,file){
var fileObj = JSON.parse(file);
var key = req.params.postId
var blogpost = fileObj[key.toString()];
var title = JSON.stringify(blogpost.blogTitle).split("\"").join("");
res.render('post',{ title: title, body: blogpost.blogpost});
});
////
});
app.listen(3000, function(){
console.log("Server is listening on Port 3000! Ready to accept requests.." );
});