title: Pausing Node.js Readable Stream
body: <p>I'm building a bar code scanning app using the node-serialport. Where I'm stuck is making a AJAX call to trigger a scan and then have Express server respond with the data from the readable stream.  </p>
  
  <p>Initialize Device:</p>
  
  <pre><code>// Open device port    
  var SerialPort = require('serialport');
  var port = '/dev/cu.usbmodem1411';
  var portObj = new SerialPort(port, (err) =&gt; {
   if(err) {
    console.log('Connection error ' + err);
   }
  });
  
  //Construct device object
  var Scanner = {
    // Trigger Scan
    scan : () =&gt; {
      portObj.write(&lt;scan cmd&gt;), (err) =&gt; {
        if(err) {
          console.log('Error on scan' + err);
        }
      });
    }
  }
  </code></pre>
  
  <p>I've tried two approaches and neither produce the 'scan-read-respond' behavior I'm looking for. </p>
  
  <p>First, I tried putting a event listener immediately following a scan, then using a callback in the listener to respond to the AJAX request. With this approach I get a 'Can't set headers after they are sent' error'. From what I understand Node is throwing this error  because res.send is being called multiple times.</p>
  
  <p>First Approach -- Response as callback in listener:</p>
  
  <pre><code>app.get('/dashboard', (req, res) =&gt; {
   Scanner.scan(); //fire scanner
   portObj.on('data', (data) =&gt; {
    res.send(data); //'Can't set headers after they are sent' error'
   });
  }
  </code></pre>
  
  <p>In the second approach, I store the scan data into a local variable ('scanned_data') and move the response outside the listener block. The problem with this approach is that res.send executes before the scanned data is captured in the local variable and so comes up as 'undefined'. Also intriguing is the scanned_data that is captured in the listener block seems to multiple with each scan.</p>
  
  <p>Second Approach -- Response outside listener:</p>
  
  <pre><code>app.get('/dashboard', (req, res) =&gt; {
    var scanned_data; //declare variable outside listener block
    Scanner.scan(); //trigger scan
    portObj.on('data', (data) =&gt; {
      scanned_data = data;
      console.log(scanned_data); //displays scanned data but data multiplies with each scan. (e.g. 3 triggers logs 'barcode_data barcode_data barcode_data')  
    });
    console.log(scanned_data); //undefined
    res.send(scanned_data);
  }
  </code></pre>
  
  <p>I'm a front end developer but have gotten to learn a lot about Node trying to figure this out. Alas, I think I've come to a dead end at this point. I tinkered with the .pipe() command, and have a hunch that's where the solution lies, but wasn't able to zero in on a solution that works. </p>
  
  <p>Any thoughts or suggestions?</p>