mock.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import express from "express";
  2. import path from "path";
  3. import bodyParser from 'body-parser'
  4. import * as fs from "fs";
  5. import fileUpload from 'express-fileupload'
  6. const staticDir = path.resolve(__dirname, "test");
  7. console.log(staticDir);
  8. let startup = false;
  9. export async function createServer(port: number) {
  10. if (startup) {
  11. return;
  12. }
  13. const app = express();
  14. app.use(express.static(staticDir));
  15. app.use(bodyParser({ limit: '200mb' }))
  16. app.use(fileUpload({createParentPath: true}))
  17. app.listen(port);
  18. startup = true;
  19. app.use((req, res, next) => {
  20. const paths = req.url.split("/")
  21. const scene = paths[1]
  22. const filename = paths[paths.length - 1]
  23. const p = path.resolve(staticDir, scene, "./attach", filename)
  24. if (req.url.includes("/upload")) {
  25. return next()
  26. } else {
  27. fs.writeFileSync(p, JSON.stringify(req.body))
  28. }
  29. res.json({code: 0, msg: 'ok'})
  30. })
  31. app.post("/:sceneCode/upload", (req, res) => {
  32. const file = (req as any).files.file
  33. const relUrl = `/attach/upload/${file.name}`
  34. const absUrl = path.resolve(staticDir, `./${req.params.sceneCode}/${relUrl}`)
  35. file.mv(absUrl, err => {
  36. if (err) {
  37. res.json({code: 1, msg: 'ok'})
  38. } else {
  39. res.json({code: 0, msg: 'ok', data: relUrl})
  40. }
  41. })
  42. })
  43. console.log("模拟环境已开启");
  44. }