title: Node.js read and write file lines
body: <p>I tried to read a file line by line, and output it to another file, using Node.js.</p>
  
  <p>My problem is the sequence of lines sometimes messed up due to async nature of Node.js.</p>
  
  <p>eg my input file is like:
  line 1
  line 2
  line 3</p>
  
  <p>but output file could be like:
  line 1
  line 3
  line 2</p>
  
  <p>Below is my code.</p>
  
  <pre><code>var fs  = require("fs");
  var index = 1;
  
  fs.readFileSync('./input.txt').toString().split('\n').forEach(
  function (line) { 
      console.log(line);
          fs.open("./output.txt", 'a', 0666, function(err, fd) {
              fs.writeSync(fd, line.toString() + "\n", null, undefined, function(err, written) {
              })});
      }
  );
  </code></pre>
  
  <p>Any thoughts would be appreciated, thanks.</p>