mongo.js 5.1 KB

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