I tried to read a file line by line, and output it to another file, using Node.js.
My problem is the sequence of lines sometimes messed up due to async nature of Nod
If you're writing a synchronous code, use only the synchronous functions:
var fs = require("fs");
fs.readFileSync('./input.txt').toString().split('\n').forEach(function (line) {
console.log(line);
fs.appendFileSync("./output.txt", line.toString() + "\n");
});
For asynchronous approach you could write something like
var fs = require('fs'),
async = require('async'),
carrier = require('carrier');
async.parallel({
input: fs.openFile.bind(null, './input.txt', 'r'),
output: fs.openFile.bind(null, './output.txt', 'a')
}, function (err, result) {
if (err) {
console.log("An error occured: " + err);
return;
}
carrier.carry(result.input)
.on('line', result.output.write)
.on('end', function () {
result.output.end();
console.log("Done");
});
});