forked from jonathanhudak/404_finder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.coffee
59 lines (48 loc) · 1.6 KB
/
server.coffee
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
# CONFIG
_ = require 'lodash'
fs = require 'fs'
chalk = require 'chalk'
express = require 'express'
bodyParser = require 'body-parser'
config = require('./lib/parseConfig')()
# CONFIG
app = express()
_DB = null
{name, port} = config
# ROUTER
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/public'))
app.get '/', (req, res) -> res.sendfile __dirname + '/public/index.html'
app.get '/api', (req, res) ->
res.setHeader('Content-Type', 'text/json')
res.send(JSON.stringify(config))
app.post '/update', (req, res) ->
res.setHeader('Content-Type', 'text/plain')
{index, item} = req.body
updateDB index, item, (db) ->
res.end(JSON.stringify(db))
# METHODS
updateDB = (key, obj, cb) ->
_DB[key] = _.assign(_DB[key], obj)
fs.writeFile __dirname + "/public/#{name}_db.json", JSON.stringify(_DB, null, '\t'), (err) =>
throw err if err isnt null
cb(_DB)
writeDB = (db, cb) ->
fs.writeFile __dirname + "/public/#{name}_db.json", JSON.stringify(db, null, '\t'), (err) =>
throw err if err isnt null
_DB = db
cb()
readDB = ->
crawl_data = require __dirname + "/log/#{name}.json"
fs.exists __dirname + "/public/#{name}_db.json", (exists) ->
if exists
db = require __dirname + "/public/#{name}_db.json"
db = _.assign(crawl_data, db)
writeDB db, startServer
else
writeDB crawl_data, startServer
startServer = ->
server = app.listen port, ->
console.log chalk.white.bgCyan "Server listening at http://localhost:#{port}"
module.exports = -> readDB()