【发布时间】:2016-11-25 06:00:48
【问题描述】:
如果每一行都满足某些条件,我需要逐行读取文件并在读取时将换行符写入同一个文件。最好的方法是什么。
【问题讨论】:
标签: node.js file-io file-handling
如果每一行都满足某些条件,我需要逐行读取文件并在读取时将换行符写入同一个文件。最好的方法是什么。
【问题讨论】:
标签: node.js file-io file-handling
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();
})
})
}
【讨论】:
在 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');
});
});
}
【讨论】: