title: simple directory listing with node.js and angular.js, watch for new files
body: <p>I have managed to create a simple angular app that lists the file contents of a folder (using a node endpoint that spits out a json). What i want to do now is to somehow get notified if a new file is added to the folder. I need this on both server and client side.</p>
  
  <p><strong>server.js:</strong></p>
  
  <pre><code>var express = require('express'),
      fs = require('fs'),
      path = require('path');
  
  var app = express();
  
  function dirTree(filename) {
      var stats = fs.lstatSync(filename),
          info = {
              path: filename,
              name: path.basename(filename)
          };
  
      if (stats.isDirectory()) {
          info.type = "folder";
          info.children = fs.readdirSync(filename).map(function(child) {
              return dirTree(filename + '/' + child);
          });
      } else {
          info.type = "file";
      }
  
      return info;
  }
  
  app.set('jsonp callback', true);
  
  app.get('/', function(req, res) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Charset','utf-8');
      res.header('Content-Type', 'application/json');
  
      var jsonp_callback = app.get('jsonp callback name');
      var jsonp = (req.query[jsonp_callback]);
      var result = dirTree('files');
      if (jsonp) {
          res.jsonp(result);
      }
      else {
          res.json(result);
      }
  });
  
  app.listen(3001);
  
  console.log('Listening on port 3001...');
  </code></pre>
  
  <p><strong>angular controller:</strong></p>
  
  <pre><code>'use strict';
  
  angular.module('myApp').controller('PageCtrl', function($scope, folderUrl, $http) {
      $http.jsonp(folderUrl).success(function(data, status, headers, config) {
          console.log(data);
          $scope.files = data.children;
      }).error(function(data, status, headers, config) {
          console.log(data, status, headers, config);
      });
  });
  </code></pre>
  
  <p>This works flawlessly. However you need to refresh the page if a new file is added to the folder. Yes the code does not cover this, and the implementation is also very minimal (using a onetime get request on controller init wont be sufficient).</p>
  
  <p><strong>So how exactly could one do this? There should be a listener on node side that would somehow emit an event that angular could catch (?)</strong>. </p>
  
  <ol>
  <li>how do i listen for "new file addition" in node.js</li>
  <li>how do i emit an event / communicate between node and angular (probably sockets)</li>
  </ol>
  
  <p>All observations are welcome!</p>
  
  <p>PS: I dont want to mix serverside and clientside logic! I need a clean communication solution / best practice</p>
  
  <p>PS2: express 4.x is used</p>