-1
我需要逐行讀取文件,並在讀取時向同一文件寫入新行,如果每行符合某些條件集。最好的辦法是什麼?一行一行地讀取一個文件,並根據它寫入新行至同一個文件 - nodejs
我需要逐行讀取文件,並在讀取時向同一文件寫入新行,如果每行符合某些條件集。最好的辦法是什麼?一行一行地讀取一個文件,並根據它寫入新行至同一個文件 - nodejs
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的幫助下使用節點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');
});
});
}