I’ve found an interesting answer to a question on Stack Overflow about how to read a file, be able to perform other operations with that information and finally write it the another file.
This is the first solution proposed:
1
2
3
4
5
6
7
8
9
10
function copyData(savPath, srcPath) {
fs.readFile(srcPath, 'utf8', function (err, data) {
if (err) throw err;
//Do your processing, MD5, send a satellite to the moon, etc.
fs.writeFile (savPath, data, function(err) {
if (err) throw err;
console.log('complete');
});
});
}
But the solutions that I prefer is that one with two separate methods:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getFileContent(srcPath, callback) {
fs.readFile(srcPath, 'utf8', function (err, data) {
if (err) throw err;
callback(data);
}
);
}
function copyFileContent(savPath, srcPath) {
getFileContent(srcPath, function(data) {
fs.writeFile (savPath, data, function(err) {
if (err) throw err;
console.log('complete');
});
});
}
Here is a post about Reading and Writing File in Node.js that explain how to use fs module for file I/O operations.