-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_file.js
More file actions
99 lines (88 loc) · 2.67 KB
/
app_file.js
File metadata and controls
99 lines (88 loc) · 2.67 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
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
var express = require('express');
var app = express(); // function object constructor -> object
var fs = require('fs');
var multer = require('multer');
app.use('/user', express.static('my-uploads'));
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'my-uploads/');
},
filename: function (req, file, cb) {
var date = new Date();
cb(null, `${file.originalname}-`+
`${date.getFullYear()}${date.getMonth()+1}${date.getDate()}_`+
`${date.getHours()}${date.getMinutes()}${date.getSeconds()}${date.getMilliseconds()}`);
}
});
var upload = multer({storage: storage})
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({
extended: false
});
const successResponse = `
Success<br>
<a href='/topic'>goto Topic</a>
`;
const TOPIC_DIR = 'data/';
app.locals.pretty = true;
app.set('views', './views');
app.set('view engine', 'pug');
app.listen(3000, function() {
console.log('Connected 3000');
});
app.get('/topic/new', (req, resp) => {
fs.readdir(TOPIC_DIR, (err, files) => {
if (err) {
resp.status(500).send('Internal Server Error');
}
resp.render('new', {topics:files});
});
});
app.post('/topic', urlencodedParser, (req, resp) => {
var title = req.body.title;
var description = req.body.description;
fs.writeFile(TOPIC_DIR + title, description, {
encoding: 'utf8',
flag: 'w'
},
(err) => {
if (err) {
resp.status(500).send('Internal Server Error');
}
resp.redirect('/topic/'+title);
});
});
app.get(['/topic', '/topic/:id'], (req, resp) => {
fs.readdir(TOPIC_DIR, (err, files) => {
var id = req.params.id;
if (err) {
resp.status(500).send('Internal Server Error');
}
if (id) {
fs.readFile(TOPIC_DIR + id, 'utf8', (err, data) => {
if (err) {
resp.status(500).send('Internal Server Error');
}
resp.render('view', {
topics: files,
title: id,
description: data
});
});
} else {
resp.render('view', {
topics: files,
title:'Welcome',
description:'Hello, JavaScript for servier'
});
}
});
});
app.get('/upload', (req, resp) => {
resp.render('upload')
});
app.post('/upload', upload.single('userfile'), (req, resp) => {
console.log(req.file)
// resp.send('uploaded: ' + req.file.filename)
resp.render('uploadview', {title: req.file.filename, path:req.file.path})
});