Mathieu2301 / TradingView-API

📈 Get real-time stocks from TradingView
1.31k stars 307 forks source link

TypeError: str.replace is not a function - Handling Buffer Input in parseWSPacket #193

Open marcin-koziel opened 1 year ago

marcin-koziel commented 1 year ago

Describe the bug The bug occurs in the parseWSPacket function, which expects a string input but receives a Buffer object instead. This leads to the TypeError: str.replace is not a function error, as the function tries to perform string operations (i.e., replace) on a Buffer object.

TypeError: str.replace is not a function

To Reproduce I tried reproducing the mentioned bug in a fresh project clone, and it worked as expected. However, the issue persists in another project using the TradingView-API, where a connection is established through the getPrivateIndicators function via WebSocket.

Expected behavior The expected behaviour of the parseWSPacket function is to correctly parse the input data (string) and return an array of TradingView packets. When receiving an input, the function should perform the string operations (i.e., replace and split) without any issues and proceed with parsing the JSON data contained in the input.

marcin-koziel commented 1 year ago

I've submitted a small fix in PR #194 to handle buffer input in the parseWSPacket function by adding a form of validation. This change shouldn't affect the main repo's functionality, as it only extends the function's capability to handle both string and buffer inputs. Even if the bug isn't immediately reproducible for others, this enhancement can only improve the code robustness and shouldn't have any negative impact.

imnotadriller commented 1 year ago

try str.toString().replace

nguyenthdat commented 1 year ago

Try this code

parseWSPacket(str) {
    if (Buffer.isBuffer(str)) {
      return str
        .toString()
        .replace(cleanerRgx, '')
        .split(splitterRgx)
        .map((p) => {
          if (!p) return false
          try {
            return JSON.parse(p)
          } catch (error) {
            console.warn('Cant parse', p)
            return false
          }
        })
        .filter((p) => p)
    }
    return str
      .replace(cleanerRgx, '')
      .split(splitterRgx)
      .map((p) => {
        if (!p) return false
        try {
          return JSON.parse(p)
        } catch (error) {
          console.warn('Cant parse', p)
          return false
        }
      })
      .filter((p) => p)
  },