index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const _ = require('underscore');
  2. const cld2 = require('./build/Release/cld');
  3. module.exports = {
  4. LANGUAGES : cld2.LANGUAGES,
  5. DETECTED_LANGUAGES : cld2.DETECTED_LANGUAGES,
  6. ENCODINGS : cld2.ENCODINGS,
  7. async detect(text, options) {
  8. let cb = arguments[2];
  9. if (typeof cb !== 'function' && typeof options === 'function') {
  10. cb = options;
  11. options = {};
  12. }
  13. try {
  14. if (arguments.length < 1) {
  15. throw new Error('Not enough arguments provided');
  16. }
  17. if (!_.isString(text) || text.length < 1) {
  18. throw new Error('Empty or invalid text');
  19. }
  20. const defaults = {
  21. isHTML : false,
  22. languageHint : '',
  23. encodingHint : '',
  24. tldHint : '',
  25. httpHint : ''
  26. };
  27. options = _.defaults({}, options, defaults);
  28. if (!_.isBoolean(options.isHTML)) {
  29. throw new Error('Invalid isHTML value');
  30. }
  31. if (!_.isString(options.languageHint)) {
  32. throw new Error('Invalid languageHint');
  33. }
  34. if (!_.isString(options.encodingHint)) {
  35. throw new Error('Invalid encodingHint');
  36. }
  37. if (!_.isString(options.tldHint)) {
  38. throw new Error('Invalid tldHint');
  39. }
  40. if (!_.isString(options.httpHint)) {
  41. throw new Error('Invalid httpHint');
  42. }
  43. if (options.encodingHint.length > 0 &&
  44. !~cld2.ENCODINGS.indexOf(options.encodingHint)) {
  45. throw new Error('Invalid encodingHint, see ENCODINGS');
  46. }
  47. if (options.languageHint.length > 0 &&
  48. !~_.keys(cld2.LANGUAGES).indexOf(options.languageHint) &&
  49. !~_.values(cld2.LANGUAGES).indexOf(options.languageHint)) {
  50. throw new Error('Invalid languageHint, see LANGUAGES');
  51. }
  52. const result = await cld2.detectAsync(
  53. text,
  54. !options.isHTML,
  55. options.languageHint,
  56. options.encodingHint,
  57. options.tldHint,
  58. options.httpHint
  59. );
  60. if (result.languages.length < 1) {
  61. throw new Error('Failed to identify language');
  62. }
  63. if (cb) {
  64. return cb(null, result);
  65. } else {
  66. return result;
  67. }
  68. } catch (error) {
  69. if (cb) {
  70. cb(error);
  71. } else {
  72. throw error;
  73. }
  74. }
  75. }
  76. };