使用deno开发post请求,get请求,监测文件变化自动重启(类似于nodemon)

9/9/2021

launch.js:

const run = () => {
  return Deno.run({
    cmd: ['deno', 'run', '--allow-net', '--allow-read', 'index.js'],
    cwd: 'app',
  })
}
let myPorcess = run()
const watcher = Deno.watchFs('./app')
for await (const event of watcher) {
  console.log(event)
  console.log('kill proceess')
  myPorcess.close()
  console.log('restart')
  myPorcess = run()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

app/index.js:

import { Application, Router, helpers } from 'https://deno.land/x/oak/mod.ts'
const app = new Application()
const router = new Router()

router.get('/list', async (ctx) => {
  const { id } = helpers.getQuery(ctx, { mergeParams: true })
  ctx.response.body = {
    state: 1,
    data: { id },
    message: '成功',
  }
})

router.post('/login', async (ctx) => {
  const result = ctx.request.body()
  console.log(66678910)
  if (result.type === 'json') {
    const { username } = await result.value
    ctx.response.body = {
      state: 1,
      data: { username },
      message: '成功',
    }
  }
})

app.use(router.routes())
app.use(router.allowedMethods())
app.listen({ port: 8000 })
console.log(8000)
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

启动命令:

deno run --allow-net --allow-read --allow-run launch.js
1

自动重启:

post请求:

get请求:

参考链接:

https://zhuanlan.zhihu.com/p/143947500 (opens new window)

https://deno-tutorial.js.org/articles/index.html (opens new window)