Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you're writing a synchronous code, use only the synchronous functions:

var fs  = require("fs");

fs.readFileSync('./input.txt').toString().split('
').forEach(function (line) { 
    console.log(line);
    fs.appendFileSync("./output.txt", line.toString() + "
");
});

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");
        });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...