nodejs encoding using request

后端 未结 3 641
面向向阳花
面向向阳花 2020-12-09 18:40

I am trying to get the correct encoding with request.

request.get({
    \"uri\":\'http://www.bold.dk/tv/\',
    \"encoding\": \"text/html;charset=\'charset=u         


        
3条回答
  •  粉色の甜心
    2020-12-09 19:28

    Maybe your trouble is in 'Accept-Encoding' header. Let's say you have Headers like 'Accept-Encoding': 'gzip,deflate'

    If it's so, you have 2 ways to fixing this:

    1. Remove this Header
    2. Use the following code to unzip the data:

      const req = request(options, res => {
          let buffers = []
          let bufferLength = 0
          let strings = []
      
          const getData = chunk => {
              if (!Buffer.isBuffer(chunk)) {
                  strings.push(chunk)
              } else if (chunk.length) {
                  bufferLength += chunk.length
                  buffers.push(chunk)
              }
          }
      
          const endData = () => {
              let response = {code: 200, body: ''}
              if (bufferLength) {
                  response.body = Buffer.concat(buffers, bufferLength)
                  if (options.encoding !== null) {
                      response.body = response.body.toString(options.encoding)
                  }
                  buffers = []
                  bufferLength = 0
              } else if (strings.length) {
                  if (options.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
                      strings[0] = strings[0].substring(1)
                  }
                  response.body = strings.join('')
              }
              console.log('response', response)
          };
      
          switch (res.headers['content-encoding']) {
              // or, just use zlib.createUnzip() to handle both cases
              case 'gzip':
                  res.pipe(zlib.createGunzip())
                      .on('data', getData)
                      .on('end', endData)
                  break;
              case 'deflate':
                  res.pipe(zlib.createInflate())
                      .on('data', getData)
                      .on('end', endData)
                  break;
              default:
                  res.pipe(zlib.createInflate())
                      .on('data', getData)
                      .on('end', endData)
                  break;
          }
      });
      

提交回复
热议问题