Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

javascript - Node.js read and write file lines

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...