热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

nodejs文本逐行读写功能的实现

利用nodejs实现:逐行读写(从一个文件逐行复制到另外一个文件);逐行读取、处理和写入(读取一行,处理后,写入另一个文件)1.所需要的模块:fs,os,readline2.具体实

利用nodejs实现:逐行读写(从一个文件逐行复制到另外一个文件);逐行读取、处理和写入(读取一行,处理后,写入另一个文件)

1.所需要的模块: fs,os,readline

2.具体实现:

 a. 功能的实现:readWriteFileByLine.js

var fs = require('fs-extra');
var os = require('os');
var rl =  require('readline');

/**
 * 按行读写,无读取内容的处理,类似单纯的复制功能
 * @param {string} readName 
 * @param {string} writeName 
 */
var readWriteFileByLine = function(readName, writeName){
    var readStream =  fs.createReadStream(readName);
    var writeStream = fs.createWriteStream(writeName);
    var readLine = rl.createInterface({
        input: readStream,
        output: writeStream,
        terminal: true
    })
}

/**
 * 按行读写,中间包涵对读取的行内容的处理
 * @param {string} readName 
 * @param {string} writeName 
 * @param {Function} callback 
 */
var readWriteFileByLineWithProcess = function(readName,writeName,callback){
    var readStream = fs.createReadStream(readName);
    var writeStream = fs.createWriteStream(writeName);
    var readLine = rl.createInterface({
        input: readStream
    })
    readLine.on('line',function(line){
        var rs = callback(line);
        writeStream.write(rs + os.EOL);
    })
}

exports.readWriteFileByLine = readWriteFileByLine;
exports.readWriteFileByLineWithProcess = readWriteFileByLineWithProcess

  b. 功能的调用:index.js

var rwByLine = require('./lib/readWriteFileByLine.js')

//按行读写,对行做字符替换处理
var readName = './obj.txt';
var writeName = './rt.txt';
rwByLine.readWriteFileByLineWithProcess(readName,writeName,function(line){
    var rs = line.toString().replace("\\",'\/');
    return rs;
})

//按行读写,无处理
readName = './obj.txt';
writeName = './rt1.txt';
rwByLine.readWriteFileByLine(readName,writeName);

 


推荐阅读
author-avatar
W于小北B
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有