Node.js读写文件行 [英] Node.js read and write file lines

查看:126
本文介绍了Node.js读写文件行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试逐行读取文件,然后使用Node.js将其输出到另一个文件。

I tried to read a file line by line, and output it to another file, using Node.js.

我的问题是有时会混乱的行序列由于Node.js的异步性质。

My problem is the sequence of lines sometimes messed up due to async nature of Node.js.

例如我的输入文件如下:
line 1
line 2
line 3

eg my input file is like: line 1 line 2 line 3

但输出文件可能如下:
line 1
line 3
line 2

but output file could be like: line 1 line 3 line 2

以下是我的代码。

var fs  = require("fs");
var index = 1;

fs.readFileSync('./input.txt').toString().split('\n').forEach(
function (line) { 
    console.log(line);
        fs.open("./output.txt", 'a', 0666, function(err, fd) {
            fs.writeSync(fd, line.toString() + "\n", null, undefined, function(err, written) {
            })});
    }
);

任何想法都会受到赞赏,谢谢。

Any thoughts would be appreciated, thanks.

推荐答案

如果您正在编写同步代码,请仅使用同步函数:

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

这篇关于Node.js读写文件行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆