title: Showing bluetooth devices in range via browser
body: <p>A simple idea. I would like to show bluetooth devices in range of the computer (using a bluetooth dongle via bluetooth-serial-port NodeJS package) in the web browser served up upon call over AJAX.</p>
  
  <p>The issue I am having is that with the following script, I can't continiously scan for devices and serve up web sites at the same time. Could you explain the workflow in this and why/what would be a good direction to rectify the issue?</p>
  
  <pre><code>var http = require("http"),
      url = require("url"),
      path = require("path"),
      fs = require("fs"),
      port = process.argv[2] || 8888,
      btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();
  
  btSerial.inquire();
  
  // Get the devices
  var devices = [];
  
  btSerial.on('found', function(address, name) {
    if(typeof devices[address] === 'undefined'){
      devices.push({'address': address,'name': name});
      console.log("Device Found: "+address+" which is named: "+name);
    }
  });
  
  // Keep searching
  btSerial.on('finished', function() {
    console.log("Done searching");
    console.log(devices);
    //btSerial.inquire();
  });
  
  
  http.createServer(function(request, response) {
  
    var uri = url.parse(request.url).pathname,
      filename = path.join(process.cwd(), uri);
  
    if (uri == '/devices') {
      response.writeHead(200, {"Content-Type": "application/json"});
      response.write(JSON.stringify(devices));
      response.end();
      return;
    }
  
    fs.exists(filename, function(exists) {
      if(!exists) {
        response.writeHead(404, {"Content-Type": "text/plain"});
        response.write("404 Not Found\n");
        response.end();
        return;
      }
  
      if (fs.statSync(filename).isDirectory()) filename += 'public/index.html';
  
      fs.readFile(filename, "binary", function(err, file) {
        if(err) {        
          response.writeHead(500, {"Content-Type": "text/plain"});
          response.write(err + "\n");
          response.end();
          return;
        }
  
        response.writeHead(200);
        response.write(file, "binary");
        response.end();
      });
    });
  }).listen(parseInt(port, 10));
  
  console.log("Static file server running at\n  =&gt; http://localhost:" + port + "/\nCTRL + C to shutdown");
  </code></pre>