recently encountered a small problem, I want to use koa to do a simple static file server. After app.listen (5050) listens on a port, I want to confirm the occupancy status of this, because the app.listen () statement may be called many times while the program is running, and if it is not possible to confirm whether the port is occupied, it may cause an error in the program.
import Koa from "koa"
import Path from "path"
import StaticServer from "koa-static"
import BodyParser from "koa-bodyparser"
import Router from "koa-router"
import Cors from "koa2-cors" // during development allow cors
import Database from "../database/index"
const app = new Koa()
let serverRouter = new Router()
let server
let data
let dataFile
app.use(Cors())
//
const staticPath = "./static"
app.use(StaticServer(Path.join(__dirname, staticPath)))
app.use(BodyParser())
//
let submit = async function (ctx) {
console.log(ctx.request.body)
ctx.response.body = {
"success": true,
"message": ""
}
let data = {
content: ctx.request.body
}
Database.insert(dataFile, data)
}
let stadata = async function (ctx) {
console.log(data)
ctx.response.body = data
}
let findsta = async function (ctx) {
let ctxparams = ctx.params
console.log("sever get request")
console.log(ctxparams.staname)
await Database.findStaByName(ctxparams.staname).then((staContent) => {
console.log(staContent)
ctx.response.body = staContent
})
}
serverRouter
.post("/api/submit", submit)
.get("/api/stadata", stadata)
.get("/api/findsta/:staname", findsta)
app.use(serverRouter.routes()).use(serverRouter.allowedMethods())
let startServer = function (arg1) {
server = app.listen(5050)
data = arg1
console.log("Your server is starting at port 5050")
}
let stopServer = function () {
server.close()
console.log("Your server is closed")
}
export default {
startServer,
stopServer
}
The main problem with is how to change the startServer function so that you can confirm the status of the port or service before calling the app.list statement.
at the same time, do you know where to find the detailed api documents of koa? This problem is because I have been in Baidu online for a long time, and I feel that I have no idea about how to use koa.
Thank you very much!