mongo.js 6.2 KB

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