逐行读取文件并基于它将新行写入同一文件 - nodejs

时间:2016-11-25 06:00:48

标签: node.js file-io file-handling

如果每行都满足某些条件,我需要逐行读取文件并在读取时将换行符写入同一文件。什么是最好的方式。

2 个答案:

答案 0 :(得分:1)

function (file, callback) {
    fs.readFile(file, (err, 'utf8', data) => {
        if (err) return callback(err);

        var lines = data.split('\n');

        fs.open(file, 'w', (err, fd) => {
            if (err) return callback(err)

            lines.forEach(line => {
                if (line === 'meet your condition') {
                    // do your write using fs.write(fd, )
                }
            })
            callback();
        })
    })
}

答案 1 :(得分:0)

在fs的帮助下使用node fs模块,您可以异步和同步地执行操作。以下是异步

的示例
function readWriteData(savPath, srcPath) {
    fs.readFile(srcPath, 'utf8', function (err, data) {
            if (err) throw err;
            //Do your processing, MD5, send a satellite to the moon or can add conditions , etc.
            fs.writeFile (savPath, data, function(err) {
                if (err) throw err;
                console.log('complete');
            });
        });
}

同步示例

function readFileContent(srcPath, callback) { 
    fs.readFile(srcPath, 'utf8', function (err, data) {
        if (err) throw err;
        callback(data);
        }
    );
}

function writeFileContent(savPath, srcPath) { 
    readFileContent(srcPath, function(data) {
        fs.writeFile (savPath, data, function(err) {
            if (err) throw err;
            console.log('complete');
        });
    });
}