-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
50 lines (43 loc) · 1.39 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
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
const filePath = req.url.substr(1);
console.log('requested URL: ', filePath)
fs.readFile(filePath, (err, data) => {
if (err) {
res.end('Error!');
res.statusCode = 404;
} else {
res.end(data);
}
})
if (req.url === '/file' && req.method === 'POST') {
let data = '';
req.on('data', (chunk) => {
data += chunk
})
req.on('end', () => {
res.statusCode = 200;
const {fileName, base64Img} = JSON.parse(data);
const file = Buffer.from(base64Img, 'base64')
fs.writeFile('./images/' + fileName, file, (err) => {
if (err) console.error(err) ;
else {
console.log('The file has been saved!');
}
});
});
}
if (req.url === '/delete-file' && req.method === 'POST') {
let data = '';
req.on('data', (chunk) => {
data += chunk;
})
req.on('end', () => {
fs.unlink('./images/' + data, (err) => {
if (err) console.error(err)
else console.log('./images/' + data, 'has been removed!');
})
})
}
}).listen(3000, () => {console.log('http://localhost:3000/index.html')});