import_unit.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. 'use strict';
  2. const readline = require('readline');
  3. const fs = require('fs');
  4. // const iconv = require('iconv-lite');
  5. const AutoDetectDecoderStream = require('autodetect-decoder-stream');
  6. const MongoClient = require('mongodb').MongoClient;
  7. // Connection URL
  8. // const url = 'mongodb://root:Ziyouyanfa%23%40!@localhost:27017';
  9. const url = 'mongodb://root:Ziyouyanfa%23%40!@192.168.18.100:27018';
  10. // const url = 'mongodb://root:Ziyouyanfa%23%40!@192.168.1.170:27018';
  11. // Database Name
  12. const dbName = 'naf';
  13. async function doWork() {
  14. const args = process.argv.splice(2);
  15. if (args.length !== 1) {
  16. console.log('请指定要导入的文件名:\n node import.js xxxx.csv');
  17. return;
  18. }
  19. console.log(`正在读取${args[0]}数据...`);
  20. const lines = await new Promise((resolve, reject) => {
  21. const res = [];
  22. const rl = readline.createInterface({
  23. // input: fs.createReadStream(args[0]).pipe(iconv.decodeStream('GBK')),
  24. // TODO: 自动检测编码
  25. input: fs.createReadStream(args[0]).pipe(new AutoDetectDecoderStream({ defaultEncoding: 'GBK' })),
  26. crlfDelay: Infinity,
  27. });
  28. rl.on('line', async line => {
  29. // console.log(line);
  30. res.push(line);
  31. });
  32. rl.on('close', () => {
  33. resolve(res);
  34. });
  35. rl.on('error', err => {
  36. reject(err);
  37. });
  38. });
  39. console.log(`共读取数据${lines.length}条!`);
  40. console.log('正在保存数据...');
  41. // Use connect method to connect to the Server
  42. const client = await MongoClient.connect(url, { poolSize: 10 });
  43. // const db = client.db(dbName).collection('naf_code_items');
  44. const db = client.db(dbName).collection('naf_unit');
  45. let count = 0;
  46. for (let i = 0; i < lines.length; i++) {
  47. const line = lines[i];
  48. const cols = line.split(',');
  49. if (cols.length < 2) continue;
  50. const data = { code: cols[0], name: cols[1], createdAt: new Date(), updatedAt: new Date(), __v: 0 };
  51. console.log(line);
  52. try {
  53. const entity = await db.findOne({ code: cols[0] });
  54. if (!entity) {
  55. await db.insertOne(data);
  56. count++;
  57. } else {
  58. await db.updateOne({ _id: entity._id }, { $set: data });
  59. console.log(`update: ${line}`);
  60. }
  61. } catch (err) {
  62. console.log(`处理错误: ${line}`);
  63. console.error(err);
  64. }
  65. }
  66. if (client) {
  67. client.close();
  68. }
  69. console.log(`导入完成,共导入${count}条数据!`);
  70. }
  71. doWork();