Node.js read and write file lines

前端 未结 3 1267
甜味超标
甜味超标 2020-12-13 03:10

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

3条回答
  •  佛祖请我去吃肉
    2020-12-13 03:27

    I suppose you want to perform some calculations and/or transformations on every line. If not, simple copy is one-liner (take a look at createReadStream documentation)

    fs.createReadStream('./input.txt').pipe(fs.createWriteStream('./output.txt'));
    

    Now, you are trying to open file each time you want to write line, and yes, order is unpredictable here. More correct version of your code:

    var lines = fs.readFileSync('./input.txt').toString().split('\n')
    function writeLineFromArray(lines) {
        var line = arr.shift();
        fs.open("./output.txt", 'a', 0666, function(err, fd) {
            fs.writeSync(fd, line + '\n', null, undefined, function(err, written) {
               writeLineFromArray(lines);
            });
        }); 
    }
    writeLinesFromArray();
    

    I'd probably use one of 'given input stream, notify me on each line' modules, for example node-lazy or byline:

    var fs = require('fs'),
        byline = require('byline');
    
    var stream = byline(fs.createReadStream('sample.txt'));
    stream.on('line', function(line) { 
        // do stuff with line
    });
    stream.pipe(fs.createWriteStream('./output');
    

提交回复
热议问题