1
0

mongo.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. const dataPath = "../assets/scripts/data"
  38. const dataPrefix = "taptapstar_"
  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. console.log('res ' + filename);
  67. return sheetsObj
  68. // console.log(XLSX.utils.sheet_to_json(ws));
  69. // console.log(workbook.SheetNames);
  70. }
  71. /**
  72. * 写入json内容到客户端assets目录
  73. * @param {String} filename 文件名
  74. * @param {Object} content json内容
  75. */
  76. const writeToAssets = function (filename, content) {
  77. let writeFileName = filename.replace(/\.xlsx|\.xls/, '.js').replace(dataPrefix, "")
  78. let writePath = path.join(__dirname, dataPath, writeFileName)
  79. fs.writeFileSync(writePath, 'module.exports=' + JSON.stringify(content))
  80. // console.log(JSON.stringify(content, null, 2));
  81. }
  82. /**
  83. * 配置表生成的json内容rsync到静态资源服务器
  84. * @param {String} filename 文件名
  85. * @param {Object} content json内容
  86. */
  87. const writeJson = function (filename, content) {
  88. let writeFileName = filename.replace(/\.xlsx|\.xls/, '.json').replace(dataPrefix, "")
  89. let writePath = path.join(__dirname, "/sheet", writeFileName)
  90. fs.writeFileSync(writePath, JSON.stringify(content))
  91. }
  92. const formatType = function(target, type) {
  93. let _type = type.toLowerCase()
  94. switch (_type) {
  95. case 'integer':
  96. target = parseInt(target, 10)
  97. break;
  98. case 'double':
  99. target = parseFloat(target)
  100. break;
  101. case 'string':
  102. target = target.toString()
  103. break;
  104. case 'object':
  105. target = JSON.parse(target)
  106. break;
  107. case 'array':
  108. target = JSON.parse(target)
  109. break;
  110. default:
  111. break;
  112. }
  113. return target
  114. }
  115. const init = function () {
  116. fs.readdir("./excel", (err, file) => {
  117. file.forEach(n => {
  118. if(n.match(/\~\$/)) {
  119. return
  120. }
  121. let ws = getSheet(n)
  122. let sheetName = n.replace(/\.xlsx|\.xls/, "")
  123. let target
  124. if(ws.length > 0) {
  125. //单个表
  126. // ws.forEach(n => {
  127. // if(typeof n['id'] != undefined) {
  128. // n['_id'] = n['id']
  129. // }
  130. // })
  131. target = ws
  132. } else {
  133. //多个表合拼成一个Array
  134. let _array = []
  135. for(let i in ws) {
  136. _array = _array.concat(ws[i])
  137. }
  138. target = _array
  139. }
  140. MongoClient.connect(connStr, connOpt, (err, client) => {
  141. var db = client.db(dbIns.dbname)
  142. var collection = db.collection(sheetName)
  143. collection.drop(null, () => {
  144. collection.insert(target, () => {
  145. console.log(`成功更新配置表:${sheetName}`)
  146. client.close()
  147. })
  148. })
  149. });
  150. //把生成的js写入客户端assets目录
  151. let wsKeys = Object.keys(ws)
  152. if(wsKeys.length == 1) {
  153. writeToAssets(n, ws[wsKeys[0]])
  154. writeJson(n, ws[wsKeys[0]])
  155. } else {
  156. writeToAssets(n, ws)
  157. writeJson(n, ws)
  158. }
  159. })
  160. // process.exit()
  161. })
  162. }
  163. init()