Advertisement
Anatolyukropov

iconv-lite

Oct 21st, 2020
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Stream-Api
  2. return new Promise(async (resolve, reject) => {
  3.     const response = await this.gotInstanse(url, gotOptions);
  4.  
  5.     const converterStream = iconv.decodeStream('win1251');
  6.     const xmlStream = await this.gotInstanse.stream(url, gotOptions);
  7.  
  8.     xmlStream.pipe(converterStream);
  9.     let xmlString = '';
  10.  
  11.     xmlStream
  12.       .on('error', error => this.logger.error(error))
  13.       .on('data', data => {
  14.         xmlString += data;
  15.       })
  16.       .on('end', () => {
  17.         if (parser.validate(xmlString) === true) {
  18.           //optional (it'll return an object in case it's not valid)
  19.           const jsonObj = parser.parse(xmlString, options);
  20.  
  21.           resolve(jsonObj);
  22.         } else {
  23.           reject({ error: 'format is not valid' });
  24.         }
  25.       });
  26.   });
  27.  
  28. Buffer-Api
  29. const { url, auth, login, password } = params;
  30.  
  31.   const gotOptions = auth ? { username: login, password } : {};
  32.  
  33.   const responsePromise = this.gotInstanse(url, gotOptions);
  34.   const bufferPromise = responsePromise.buffer();
  35.  
  36.   try {
  37.     const [response, buffer] = await Promise.all([responsePromise, bufferPromise]);
  38.     let parseString = response.body;
  39.  
  40.     if (
  41.       response.headers['content-type'].includes('windows-1251') ||
  42.       response.headers['content-type'].includes('cp1251')
  43.     ) {
  44.       parseString = iconv.decode(buffer, 'win1251');
  45.     }
  46.  
  47.     return parser.parse(parseString, options);
  48.   } catch (err) {
  49.     throw new Error(err);
  50.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement