TooTallNate / node-icy

Node.js module for parsing and/or injecting ICY metadata
MIT License
291 stars 48 forks source link

How to catch timeout events? #39

Open nikmartin opened 5 years ago

nikmartin commented 5 years ago

I'm setting up my icy reader like:

 const opts: any = {};
    opts.hostname = myURL.hostname;
    opts.port = myURL.port;
    opts.timeout = 3000;
    opts.path = myURL.pathname;
    opts.protocol = myURL.protocol;
    // connect to the remote stream
    icy.get(opts, function(response) {
      const streamObj: any = {};

      if (response.headers['icy-name']) {
        streamObj.streamName = response.headers['icy-name'];
      }

      if (response.headers['icy-url']) {
        streamObj.streamUrl = response.headers['icy-url'];
      }

      // log any "metadata" events that happen
      response.once('metadata', (metadata: any) => {
        const parsed = icy.parse(metadata);
        if (parsed['StreamTitle']) {
          streamObj.streamTitle = parsed['StreamTitle'];
        }
        if (parsed['StreamUrl']) {
          streamObj.streamUrl = parsed['StreamUrl'];
        }
        //console.log(streamObj);
        res.status(200).send(streamObj);
        return;
      });

      response.once('timeout', (err: any) => {
        console.log('timeout');
        res.status(400).end(err);
        return;
      });

      response.once('end', (err: any) => {
        console.log('end');
        res.status(200).end('end');
        return;
      });
      response.resume();
    });

But if node-icy connects to a bad url, or one that doesn't respond, the connection never times out. Should I be listening for something other than 'timeout'?

kyjus25 commented 5 years ago

+1 wondering this.

I have process.on('uncaughtException', function (err) { console.log('Caught exception: ', err); });

And not sure how to gracefuly send a 400 response on error

roomtek commented 3 years ago

you need to use the returned client object, and add listeners like this:

let client = icy.get(.....);
......
client.on("error", () => { res.status(400).end(err); });
client.on("timeout", () => { res.status(400).end(err); });