test.app.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Created by Wu Jian Ping on - 2022/07/22.
  3. */
  4. const Searcher = require('../')
  5. const { ArgumentParser } = require('argparse')
  6. // 处理输入参数
  7. const parser = new ArgumentParser({
  8. add_help: true,
  9. description: 'ip2region test app',
  10. prog: 'node test.app.js',
  11. usage: 'Usage %(prog)s [command options]'
  12. })
  13. parser.add_argument('--db', { help: 'ip2region binary xdb file path, default: ../../data/ip2region.xdb' })
  14. parser.add_argument('--cache-policy', { help: 'cache policy: file/vectorIndex/content, default: content' })
  15. const args = parser.parse_args()
  16. const dbPath = args.db || '../../data/ip2region.xdb'
  17. const cachePolicy = args.cache_policy || 'content'
  18. // 创建searcher对象
  19. const createSearcher = () => {
  20. let searcher = null
  21. let vectorIndex = null
  22. let buffer = null
  23. switch (cachePolicy) {
  24. case 'file':
  25. searcher = Searcher.newWithFileOnly(dbPath)
  26. break
  27. case 'vectorIndex':
  28. vectorIndex = Searcher.loadVectorIndexFromFile(dbPath)
  29. searcher = Searcher.newWithVectorIndex(dbPath, vectorIndex)
  30. break
  31. default:
  32. buffer = Searcher.loadContentFromFile(dbPath)
  33. searcher = Searcher.newWithBuffer(buffer)
  34. }
  35. console.log('options: ')
  36. console.log(` dbPath: ${dbPath}`)
  37. console.log(` cache-policy: ${cachePolicy}`)
  38. console.log('')
  39. return searcher
  40. }
  41. // 从控制台读取用户一行输入
  42. const readlineSync = () => {
  43. return new Promise((resolve, reject) => {
  44. process.stdin.resume()
  45. process.stdin.on('data', data => {
  46. process.stdin.pause()
  47. resolve(data.toString('utf-8'))
  48. })
  49. })
  50. }
  51. const searcher = createSearcher()
  52. const main = async () => {
  53. console.log('type \'quit\' to exit')
  54. while (true) {
  55. process.stdout.write('ip2region>> ')
  56. const ip = (await readlineSync()).trim()
  57. if (ip === 'quit') {
  58. process.exit(0)
  59. } else {
  60. try {
  61. const response = await searcher.search(ip)
  62. console.log(response)
  63. } catch (err) {
  64. console.log(err)
  65. }
  66. }
  67. }
  68. }
  69. main()