title: ENFILE: File table overflow Node.js
body: <p>I am trying to make a more memory efficient prime number generator. I can't think of anything better than using a file as my prime number array, and read line by line synchronously. I run this and at about 29000 it gives me the <code>ENFILE: File table overflow</code> error. Any ideas to fix/improve this code?</p>
  
  <p><a href="https://github.com/nickewing/line-reader" rel="nofollow">This is the library I'm using</a></p>
  
  <pre class="lang-js prettyprint-override"><code>#!/usr/bin/env node
  
  var num = 3,
      prime,
      fs = require("fs"),
      readline = require("./line_reader.js");
  
  console.log("Hundreds: 2");
  console.log("Hundreds: 3");
  
  function appendPrime (num) {
    fs.appendFileSync("Primes.txt", num+'\n');
  }
  
  while (true) {
    prime = true;
    var times = Math.floor(Math.pow(num, 0.5));
    if (num % 2 == 0 || num % 3 == 0) {
      prime = false;
    } else {
      readline.eachLine("Primes.txt", function (line, last, cb) {
        if (num % line == 0) {
          prime = false;
          cb(true);
        } else {
          cb();
        }
      });
    }
    if (prime) {
      var place = String(num).length;
      switch (true) {
        case place &lt;= 3:
          console.log("Hundreds: "+num);
        break;
        case place &lt;= 5 :
          console.log("Thousands: "+num);
        break;
        case 6 :
          console.log("Hundred thousands: "+num);
        break;
        case place &lt;= 8 :
          console.log("Millions: "+num);
        break;
        case 9 :
          console.log("Hundred millions: "+num);
        break;
        case place &gt;= 10 :
          console.log("Billions or above: "+num);
        break;
      }
      appendPrime(num);
    }
    num += 2;
  }
  </code></pre>