-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
107 lines (90 loc) · 2.98 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
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
const Koa = require('koa'),
router = require('koa-router')(),
serve = require('koa-static'),
mount = require('koa-mount'),
views = require('koa-views'),
koaBody = require('koa-body'),
fs = require('fs'),
io = require('socket.io')(),
api = new Koa(),
apiPort = 9001,
socketPort = 9002,
projectPath = 'C:/Users/apple/Documents/work/dev/sketchup/floorplandetect', // 项目路径
pluginName = 'FloorPlanPlugin' // 插件名称
let client = null
const initSocket = (port) => {
io.on('connection', (d) => {
client = d
client.on('event', (data) => {
console.log(data)
})
client.on('disconnect', (socket) => {
console.log('关闭连接:' + socket)
})
})
io.listen(port || 9002)
}
const initApiServer = (port) => {
router.get('/', async (ctx, next) => {
await apiHandler(ctx)
})
router.get('/update', async (ctx, next) => {
let code = fs.readFileSync('./output.rb', {encoding: 'utf-8'})
ctx.body = {
code: code
}
})
router.post('/setting', koaBody(), async (ctx, next) => {
initWatchFileServer(ctx.request.body.watchingFile, ctx.request.body.watchingPath)
ctx.body = await ctx.request.body
})
api
.use(mount('/node_modules', serve(__dirname + '/node_modules')))
.use(views(__dirname + '/html', {extension:'pug'}))
.use(router.routes())
.use(router.allowedMethods())
api.listen(port || 9001)
console.log(`开启接口服务器,端口号:${port}`)
}
// API处理
const apiHandler = async (ctx) => {
let code = fs.readFileSync('./output.rb', {encoding: 'utf-8'})
let loadpath = fs.readFileSync('./loadpath.txt', {encoding: 'utf-8'})
return ctx.render('index', {
params: {
socketPort: socketPort,
code: code,
loadpath: loadpath
}
})
}
const initWatchFileServer = (entryFilename, path) => {
fs.writeFileSync('loadpath.txt', path)
// 初始化读取代码
let script = fs.readFileSync(`${path}/${entryFilename}`, {
encoding: 'utf-8'
})
fs.writeFileSync('./output.rb', script, {encoding:'utf-8'})
fs.watch(path, null, (eType, filename) => {
console.log(`${eType} ======= ${filename}`)
let script = fs.readFileSync(`${path}/${filename}`, {
encoding: 'utf-8'
})
if(filename === entryFilename) {
fs.writeFileSync('./output.rb', script,{encoding:'utf-8'})
client.emit('event', {
event: 'entry',
message: 'entry code changed'
})
} else {
client.emit('event', {
event: 'other',
file: filename,
message: `${filename} has changed`
})
}
})
}
initSocket(socketPort)
initApiServer(apiPort)
// initWatchFileServer(`${pluginName.toLowerCase()}.rb`, `${projectPath}/skpsrc/${pluginName}`)