mongo.js 4.6 KB

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