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 Node.js.
eg my input file is like:
line 1
line 2
line 3
but output file could be like:
line 1
line 3
line 2
Below is my code.
var fs = require("fs");
var index = 1;
fs.readFileSync('./input.txt').toString().split('
').forEach(
function (line) {
console.log(line);
fs.open("./output.txt", 'a', 0666, function(err, fd) {
fs.writeSync(fd, line.toString() + "
", null, undefined, function(err, written) {
})});
}
);
Any thoughts would be appreciated, thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…