mongo.js 4.0 KB

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