title: How to detect if net.Socket connection dies - node.js
body: <h2>Background</h2>
  
  <p>I am communicating with a machine using <a href="https://nodejs.org/api/net.html" rel="noreferrer"><code>net.Socket</code></a> via TCP/IP. </p>
  
  <p>I am able to establish the connection and to send and receive packets of Buffers, which is all fine. </p>
  
  <h2>Problem</h2>
  
  <p>The problem is that if I manually disconnect the internet cable from the machine, my Node.js connection doesn't fire the <code>close</code> event and I have no means to know if something failed!</p>
  
  <h2>Code</h2>
  
  <pre><code>let socket;
  
  const start = async function ( config ) {
  
      await connecToBarrier( config )
          .then( () =&gt; console.log( "connected to barrrier" ) )
          .catch( err =&gt; {
              throw new Error( `Cannot connect to barrier: ${err}` );
          } );
  };
  
  const connecToBarrier = function ( connectOpts ) {
      return new Promise( ( resolve, reject ) =&gt; {
          //connectOpts is an object with 'port' and 'host'
          socket = net.createConnection( connectOpts, () =&gt; {
              //once I receive a 'hello world' from the machine, I can continue
              socket.once( "data", () =&gt; resolve() );
          } );
  
          socket.on( "connection", () =&gt; {
              console.log("onConnection says we have someone!");
          } );
  
          socket.on( "error", err =&gt; {
              console.log(`onError says: ${err}`);
              reject(err);
          } );
  
          socket.on( "timeout", () =&gt; {
              console.log("onTimeout says nothing");
              reject();
          } );
  
          socket.on( "end", () =&gt; {
              console.log("onEnd says nothing");
              reject();
          } );
  
          socket.on( "close", err =&gt; {
              console.log(`onClose says: ${err}`);
              reject(err);
          } );
      } );
  };
  
  
  start();
  </code></pre>
  
  <h2>Research</h2>
  
  <p>@robertklep mentioned the <code>setKeepAlive</code> option, however according to </p>
  
  <p><a href="https://stackoverflow.com/questions/20561596/how-to-test-socket-setkeepalive-in-nodejs">How to test socket.setKeepAlive in NodeJS</a></p>
  
  <p>it doesn't work. A more profound research shows that this is highly dependant on the Operative System you are using, as per <a href="https://stackoverflow.com/a/18678494/1337392">https://stackoverflow.com/a/18678494/1337392</a></p>
  
  <p>So in other words, unless I am willing to wait several minutes for my heartbeats to actually do something, I don't see a way out of this.</p>
  
  <h2>Question</h2>
  
  <p>How do I detect if a connection died?</p>