Răsfoiți Sursa

优化代码,修复内存数据丢失问题

zhusiqing 4 ani în urmă
părinte
comite
ea8e382677
2 a modificat fișierele cu 25 adăugiri și 11 ștergeri
  1. 6 0
      server/config.js
  2. 19 11
      server/server.js

+ 6 - 0
server/config.js

@@ -2,6 +2,11 @@ const path = require('path')
 
 const resolve = filePath => path.resolve(__dirname, filePath)
 
+const ports = {
+  appPort: 5555,
+  wsPort: 5556
+}
+
 const routerOptions = {
   prefix: '/api'
 }
@@ -24,6 +29,7 @@ const filePath = {
 }
 
 const config = {
+  ports,
   routerOptions,
   lruOptions,
   watchFileOptions,

+ 19 - 11
server/server.js

@@ -6,21 +6,29 @@ const bodyParser = require('koa-bodyparser')
 const LRU = require('lru-cache')
 const WebSocket = require('ws')
 const koaStatic = require('koa-static')
-const { routerOptions, lruOptions, watchFileOptions, filePath } = require('./config')
+const { routerOptions, lruOptions, watchFileOptions, filePath, ports } = require('./config')
 
 const { dataPath, reviewDataPath, staticPath } = filePath
+const { appPort, wsPort } = ports
 
 const router = new Router(routerOptions)
 const cache = new LRU(lruOptions)
 
 let STATIC_DATA = ''
-fs.readFile(dataPath, (err, buf) => {
-  if (err) {
-    console.error(err)
-    return
-  }
-  STATIC_DATA = buf.toString().replace('\n', '').split(',')
-})
+const readFile = () => {
+  fs.readFile(dataPath, (err, buf) => {
+    if (err) {
+      console.error(err)
+      return
+    }
+    STATIC_DATA = buf.toString().replace('\n', '').split(',')
+  })
+}
+readFile()
+
+setInterval(() => {
+  readFile()
+}, 60 * 60 * 24e3)
 
 fs.watchFile(dataPath, watchFileOptions, (curr, prev) => {
   if (curr.mtime !== prev.mtime) {
@@ -36,7 +44,7 @@ fs.watchFile(dataPath, watchFileOptions, (curr, prev) => {
 })
 
 const app = new Koa()
-const wss = new WebSocket.Server({ port: 5556 })
+const wss = new WebSocket.Server({ port: wsPort })
 
 app.use(koaStatic(path.join(__dirname, staticPath)))
 
@@ -194,6 +202,6 @@ app.use(router.routes()).use(router.allowedMethods())
 
 app.on('error', err => console.error(err))
 
-app.listen(5555)
+app.listen(appPort)
 
-console.log('http://127.0.0.1:5555')
+console.log(`http://127.0.0.1:${appPort}`)