-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
186 lines (164 loc) · 4.94 KB
/
index.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// Setup Express
var http = require('http');
var express = require("express");
var app = express();
var path = require('path');
const devIp = require('dev-ip')
let port
var uploadsDir = __dirname + '/public/uploads';
var ufn = require('unique-file-name')({
// Slugified file name, followed optionally by an integer (to keep names
// unique), followed by the slugified extension.
format: '%b%i%e',
dir: uploadsDir
});
var multer = require('multer');
var storage = multer({
storage: multer.diskStorage({
destination: uploadsDir,
filename: function (req, file, cb) {
// Write an empty file, then have multer overwite it
const oldName = file.originalname
ufn(oldName, function(err, fullPath){
if(err) return cb(err);
const newName = path.basename(fullPath)
console.log('Saving file ' + oldName + (newName == oldName ? '' : ' as ' + newName))
cb(null, path.basename(fullPath));
});
}
})
});
app.use(require("body-parser").json());
var fs = require("fs");
// Declare an array for uploaded text
var uploadedText = [];
// Configure views
app.set("views", path.join(__dirname, 'views'));
app.set("view engine", "pug");
// Server static files
app.use("/assets", express.static(path.join(__dirname, 'public', 'assets')));
// GET pages
app.get('/', function(req, res) {
const ip = devIp()[0]
const url = ip && port ? `http://${ip}:${port}` : null
res.render('index', {url});
});
app.get("/upload", function(req, res){
res.render("upload");
});
app.get("/download", function(req, res){
// Find uploaded files
listUploads(function(files){
res.render("download", {text: uploadedText, files: files});
});
});
app.get("/uploads/:file", function(req, res){
console.log('Downloading file ' + req.params.file)
res.download(__dirname + "/public/uploads/" + req.params.file);
});
// POST data
app.post("/upload", storage.array('files[]'), function(req, res){
// Files are automatically saved by multer
// Save text
if(req.body.text) addText(req.body.text);
// See whether files or text was uploaded
var text = !!req.body.text, files = req.files.length > 0;
var msg, success;
// If something was uploaded
if(text || files) {
success = true;
msg = 'Successfully uploaded ';
var fileMsg;
if(files) {
var count = req.files.length;
fileMsg = count + (count == 1 ? ' file' : ' files');
}
if(text && files) msg += 'text and ' + fileMsg + '.';
else if(text && !files) msg += 'text.';
else msg += fileMsg + '.';
}
else {
msg = "Nothing was uploaded.";
success = false;
}
listUploads(function(list){
res.render("download",
{
msg: msg,
success: success,
text: uploadedText,
files: list
});
});
});
app.use(function(req, res) {
res.render('error', {
error: {
status: 404, message: 'Page not found'
}
})
})
app.use(function(err, req, res, next) {
err.status = 500
err.message = 'Internal server error'
res.status(500)
res.render('error', {error: err})
})
var server = http.createServer(app);
server.on('listening', function() {
port = server.address().port
console.log('Local URL: http://localhost:' + port)
const ip = devIp()
if(ip[0]) console.log(`External URL: http://${devIp()}:${port}`)
else console.log('Unable to find external IP address. Perhaps you are offline?')
console.log('--------------------')
});
server.on('error', function(err){
// If the port was specified, throw an error for the failed binding
if(process.env.PORT) throw new Error('Could not bind to specified port ' + process.env.PORT);
// Try the next port if this one is in use
else if(err.code === 'EADDRINUSE') {
server.listen(err.port + 1);
}
else throw err;
});
server.listen(process.env.PORT || 3000);
// Saves a new piece of uploaded text
function addText(text){
uploadedText.push(text);
fs.writeFile(__dirname + "/public/uploaded_text.json",
JSON.stringify(uploadedText),
function(err) {if(err) throw err;});
}
fs.readFile(__dirname + "/public/uploaded_text.json",
"utf8",
function(err, data){
if(err && err.code != "ENOENT") throw err;
else if (data) uploadedText = JSON.parse(data);
});
// Calls cb with an array of files in public/uploads
// Each element has a name and url
function listUploads(cb){
var list = [];
var dir = __dirname + "/public/uploads/";
// List files and dirs
fs.readdir(dir, function(err, files){
// The dir doesn't have to exist
if(err && err.code == "ENOENT") return [];
else if(err) throw err;
// Check each to see if it's a file
for(var i = 0; i < files.length; i++){
// If it's a file, add it to the list
if(!fs.statSync(dir + files[i]).isDirectory()){
list.push(
{
name: files[i],
url: "/uploads/"+files[i]
}
);
}
}
// Send the list to the callback
cb(list);
});
}