title: Node js incoming tls socket closing when run in background or service
body: <p>I have a node js server.js I run on a EC2 instance (ubuntu). This server opens a TLS socket connection to a third party streaming API. When executed in the foreground it runs as expected (ie socket connects and stays open receiving data or heartbeat).</p>
  
  <p>However, I would like to run it in the background so it continues running when I disconnect my shell. I have tried running the following commands, all of which run the script, receive a socket connection message and within 30ms immediately close the socket (.on('end'...)):</p>
  
  <pre><code>node server.js &amp;
  node server.js &lt;/dev/null
  nohup node server.js &amp;
  </code></pre>
  
  <p>I have also tried setting it up in systemd as service to run with systemctl start [service]. All yield the same result. </p>
  
  <p>What am I missing? </p>
  
  <p>TLS code snippet:</p>
  
  <pre><code>const port = 443;
  const hostname = 'third-party-host.com';
  const tls = require('tls');
  var body = '';
  
  const options = {
    host: hostname,
    port: port
  };
  
  socket = tls.connect(options, () =&gt; {
    logger.info('client connected',
                socket.authorized ? 'authorized' : 'unauthorized');
    process.stdin.pipe(socket);
    process.stdin.resume();
  })
  
  .setEncoding('utf8')
  
  var body = '';
  socket.on('data', function(chunk) {
    if (chunk.slice(-2) == "\r\n"){
      body += chunk.toString();
      logger.verbose(body);
      ...
      body = '';
    } else {
      body += chunk.toString();
    }
  })
  
  socket.on('end', function() {
      logger.warn("Socket closed");
  });
  </code></pre>
  
  <p><strong>UPDATED:</strong></p>
  
  <p>Could the issue be related to process.stdin not accepting input when running in background?
  <a href="https://stackoverflow.com/questions/21074452/nodejs-read-stdin-from-background-process">Previous issue I found</a></p>