Home How to read a file and write it again with separate functions with node.js
Post
Cancel

How to read a file and write it again with separate functions with node.js

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.

This post is licensed under CC BY 4.0 by the author.