mongo.js 5.6 KB

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