title: Consecutive writings to several files in the server
body: <p>(* As <a href="https://stackoverflow.com/questions/42364694/consecutive-writings-to-files-in-the-server-are-slow">my previous question</a> has been more or less answered, and the code has evolved, I open a new question. *)</p>
  
  <p>I want to build a simple playground with MEAN stack that mimics plunker: we have a list of files and a textarea on the left hand, and a live preview on the right hand. Note that the files are saved in a temporary folder, and the live preview is an <code>iframe</code> injected by the files from that temporary folder.</p>
  
  <p><a href="https://i.stack.imgur.com/WlXGm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WlXGm.png" alt="enter image description here"></a></p>
  
  <p>********** what I have written **********</p>
  
  <p>In the html file, I add one controller per file, so that I could track exactly which file is changed in the textarea. Then, I just need to save that file to the server, rather than all the files:</p>
  
  <pre><code>&lt;div ng-repeat="file in files track by $index" ng-controller="fileCtrl"&gt;
      &lt;a ng-click="go(file)"&gt;{{file.name}}&lt;/a&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>the controller:</p>
  
  <pre><code>app.controller('fileCtrl', ['$scope', 'codeService', function ($scope, codeService) {
      $scope.$watch('file', function () {
          codeService.render($scope.files, $scope.file);
      }, true);
  }]);
  </code></pre>
  
  <p>the <code>codeService</code>:</p>
  
  <pre><code>app.service('codeService', ['$http', function ($http) {
      this.render = function (files, changedFile) {
          $http.post('/writeFile', changedFile);
      };
  }]);
  </code></pre>
  
  <p>the router:</p>
  
  <pre><code>router.post('/writeFile', function (req, res, next) {
      var file = req.body;
      var fs = require('fs');
      fs.writeFile("public/tmp/" + file.name, file.body, function (err) {
          if (err) { return console.log(err) };
      });
  });
  </code></pre>
  
  <p>********** my tests **********</p>
  
  <p>My tests show that the modification in the textarea is well caught, and the modified file can more or less be saved to the server: <strong>it works quite well for the 1st, 2nd writings, but it often has trouble for the writings that follow</strong>.</p>
  
  <p>********** my questions **********</p>
  
  <p>Could anyone help me re-structure the code to handle well:</p>
  
  <ol>
  <li>asynchronous calls of writings, such that all the writings are well (and fast) undertaken. </li>
  <li>writings with <code>debounce</code>, that means we could wait a little bit before each saving. But it's a little bit tricky when we have several files: assume we could switch among files <strong>very fast</strong>, how would <code>debounce</code> and asynchronous saving perform in that case?</li>
  </ol>