mongo.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. const fs = require('fs')
  2. const path = require('path')
  3. const XLSX = require('xlsx')
  4. // const Rsync = require('rsync')
  5. const {MongoConf} = require('./config')
  6. const MongoClient = require('mongodb').MongoClient
  7. const assert = require('assert')
  8. const dbIns = MongoConf['R1']
  9. const connStr = `mongodb://${dbIns.host}:${dbIns.port}`
  10. const connOpt = {
  11. auth : {
  12. user: dbIns.username,
  13. password: dbIns.password,
  14. },
  15. authSource: dbIns.dbname,
  16. authMechanism: "SCRAM-SHA-1",
  17. useNewUrlParser: true
  18. }
  19. const dataPath = "../assets/scripts/data"
  20. const dataPrefix = "allstar_"
  21. /**
  22. * excel表转换为json对象
  23. * @param {String} filename 文件名
  24. */
  25. const getSheet = function (filename) {
  26. let filePath = path.join(__dirname, "/excel", filename)
  27. // let buf = fs.readFile(filePath);
  28. let workbook = XLSX.readFileSync(filePath)
  29. let sheets = workbook.SheetNames
  30. let sheetsObj = {}
  31. sheets.forEach(n => {
  32. let ws = workbook.Sheets[n]
  33. let def = XLSX.utils.sheet_to_json(ws, {range: 0, header: 1})
  34. let typeMap = {}
  35. let typeArr = def[0]
  36. let keyArr = def[2]
  37. keyArr.forEach((item, index) => {
  38. typeMap[item] = typeArr[index]
  39. })
  40. let res = XLSX.utils.sheet_to_json(ws, {range: 2})
  41. res.forEach(item => {
  42. for(let i in item) {
  43. item[i] = formatType(item[i], typeMap[i])
  44. }
  45. })
  46. sheetsObj[n] = res
  47. })
  48. return sheetsObj
  49. // console.log(XLSX.utils.sheet_to_json(ws));
  50. // console.log(workbook.SheetNames);
  51. }
  52. /**
  53. * 写入json内容到客户端assets目录
  54. * @param {String} filename 文件名
  55. * @param {Object} content json内容
  56. */
  57. const writeToAssets = function (filename, content) {
  58. let writeFileName = filename.replace(/\.xlsx|\.xls/, '.js').replace(dataPrefix, "")
  59. let writePath = path.join(__dirname, dataPath, writeFileName)
  60. fs.writeFileSync(writePath, 'module.exports=' + JSON.stringify(content))
  61. // console.log(JSON.stringify(content, null, 2));
  62. }
  63. /**
  64. * 配置表生成的json内容rsync到静态资源服务器
  65. * @param {String} filename 文件名
  66. * @param {Object} content json内容
  67. */
  68. const writeJson = function (filename, content) {
  69. let writeFileName = filename.replace(/\.xlsx|\.xls/, '.json').replace(dataPrefix, "")
  70. let writePath = path.join(__dirname, "/sheet", writeFileName)
  71. fs.writeFileSync(writePath, JSON.stringify(content))
  72. }
  73. const formatType = function(target, type) {
  74. let _type = type.toLowerCase()
  75. switch (_type) {
  76. case 'integer':
  77. target = parseInt(target, 10)
  78. break;
  79. case 'double':
  80. target = parseFloat(target)
  81. break;
  82. case 'string':
  83. target = target.toString()
  84. break;
  85. case 'object':
  86. target = JSON.parse(target)
  87. break;
  88. case 'array':
  89. target = JSON.parse(target)
  90. break;
  91. default:
  92. break;
  93. }
  94. return target
  95. }
  96. const init = function () {
  97. fs.readdir("./excel", (err, file) => {
  98. file.forEach(n => {
  99. if(n.match(/\~\$/)) {
  100. return
  101. }
  102. let ws = getSheet(n)
  103. let sheetName = n.replace(/\.xlsx|\.xls/, "")
  104. let target
  105. if(ws.length > 0) {
  106. //单个表
  107. // ws.forEach(n => {
  108. // if(typeof n['id'] != undefined) {
  109. // n['_id'] = n['id']
  110. // }
  111. // })
  112. target = ws
  113. } else {
  114. //多个表合拼成一个Array
  115. let _array = []
  116. for(let i in ws) {
  117. _array = _array.concat(ws[i])
  118. }
  119. target = _array
  120. }
  121. MongoClient.connect(connStr, connOpt, (err, client) => {
  122. var db = client.db(dbIns.dbname)
  123. var collection = db.collection(sheetName)
  124. collection.drop(null, () => {
  125. collection.insert(target, () => {
  126. console.log(`成功更新配置表:${sheetName}`)
  127. client.close()
  128. })
  129. })
  130. });
  131. //把生成的js写入客户端assets目录
  132. let wsKeys = Object.keys(ws)
  133. if(wsKeys.length == 1) {
  134. writeToAssets(n, ws[wsKeys[0]])
  135. writeJson(n, ws[wsKeys[0]])
  136. } else {
  137. writeToAssets(n, ws)
  138. writeJson(n, ws)
  139. }
  140. })
  141. // process.exit()
  142. })
  143. }
  144. init()