lang.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import express from 'express'
  2. import path from 'path'
  3. import bodyParser from 'body-parser'
  4. import * as fs from 'fs'
  5. import { fileURLToPath } from 'url'
  6. const __filename = fileURLToPath(import.meta.url)
  7. const __dirname = path.dirname(__filename)
  8. const startup = false
  9. const enter = `
  10. import { modulesParse } from '../helper'
  11. const { ctx, promise } = modulesParse(
  12. import.meta.glob(['./*.ts', '!./index.ts'])
  13. )
  14. export default ctx
  15. export { promise }
  16. `
  17. const writeFile = (path, content) =>
  18. new Promise((resolve, reject) => {
  19. fs.writeFile(path, content, err => {
  20. if (err) {
  21. reject(err)
  22. } else {
  23. resolve()
  24. }
  25. })
  26. })
  27. const langDir = path.join(__dirname, '../src/lang')
  28. const writeLang = (name, lang) => {
  29. const dir = path.join(langDir, name)
  30. if (!fs.existsSync(dir)) {
  31. fs.mkdirSync(dir)
  32. }
  33. return Promise.all([
  34. writeFile(path.join(dir, 'index.ts'), enter),
  35. ...Object.entries(lang).map(([name, content]) =>
  36. writeFile(
  37. path.join(dir, `${name}.ts`),
  38. `export default ${JSON.stringify(content, null, 4)}`
  39. )
  40. )
  41. ])
  42. }
  43. export async function createServer(port) {
  44. if (startup) {
  45. return
  46. }
  47. const app = express()
  48. app.use('/dev', bodyParser.json())
  49. app.use('/dev', bodyParser.urlencoded({ extended: false }))
  50. app.post('/dev/langs', async function (req, res) {
  51. const langs = req.body
  52. const handlers = Object.entries(langs).map(([name, lang]) =>
  53. writeLang(name, lang)
  54. )
  55. Promise.all(handlers)
  56. .then(() => res.json({ ok: true }))
  57. .catch(() => res.json({ ok: false }))
  58. })
  59. app.listen(port)
  60. console.log('语言编辑已开启')
  61. }