import.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 !== 2) {
  16. console.log('请指定要导入的文件名和类别:\n node import.js xxxx.csv 31');
  17. return;
  18. }
  19. const category = args[1];
  20. console.log(`正在读取${args[0]}数据...`);
  21. const lines = await new Promise((resolve, reject) => {
  22. const res = [];
  23. const rl = readline.createInterface({
  24. // input: fs.createReadStream(args[0]).pipe(iconv.decodeStream('GBK')),
  25. // TODO: 自动检测编码
  26. input: fs.createReadStream(args[0]).pipe(new AutoDetectDecoderStream({ defaultEncoding: 'GBK' })),
  27. crlfDelay: Infinity,
  28. });
  29. rl.on('line', async line => {
  30. // console.log(line);
  31. res.push(line);
  32. });
  33. rl.on('close', () => {
  34. resolve(res);
  35. });
  36. rl.on('error', err => {
  37. reject(err);
  38. });
  39. });
  40. console.log(`共读取数据${lines.length}条!`);
  41. console.log('正在保存数据...');
  42. // Use connect method to connect to the Server
  43. const client = await MongoClient.connect(url, { poolSize: 10, useNewUrlParser: true });
  44. const db = client.db(dbName).collection('naf_code_items');
  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], category, group: '0', stauts: '0', order: 0 };
  51. console.log(line);
  52. try {
  53. const entity = await db.findOne({ code: cols[0], category });
  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();