-1

what is the difference between fs.copyFile() and fs.copyFileSync() in node.js

fs.copyFile("a.txt", "b.txt", (err) => {
  if (err) throw err;
  console.log("file is copied to the destination");
});

code
  • 5,690
  • 4
  • 17
  • 39
  • Instead of taking a callback, `fs.copyFileSync` is blocking and forces the proceeding code to wait. No other code is run in that thread at that time. This behavior is consistent with other functions such as `readFileSync`, `writeFileSync`, or `readDirSync`. It dedicates the entire thread to this job, so you have to be careful if you're writing web servers as it would block other requests from executing, causing slower server load times. – code Nov 14 '22 at 05:55
  • we know node is single thread so what will be your choice async or sync – Nisal Jayathilaka Nov 14 '22 at 05:59
  • 1
    Depends on what you’re writing. A single-user command line tool? Then it doesn’t matter, but the sync version makes for slightly easier code. Or a multi-user web server? Then definitely the async version. – deceze Nov 14 '22 at 06:03

1 Answers1

1

fs.copyFile is used for asynchronous process whereas fs.copyFileSync is used for synchronous process.

Example of fs.copyFile (asynchronous) :

In this the tasks which gets completed first will give output.

Task - 1 : (fs.copyFile) takes 5s to complete.
Task - 2 : (fs.copyFile) takes 6s to complete.
Task - 3 : (fs.copyFile) takes 1s to complete.

Output :

Task - 3 -> Task - 1 -> Task - 2

Example of fs.copyFileSync (synchronous) :

In this order will be maintained. Like After completion of first task then it will go for next task and so on.

Task - 1 : (fs.copyFileSync) takes 5s to complete.
Task - 2 : (fs.copyFileSync) takes 6s to complete.
Task - 3 :(fs.copyFileSync) takes 1s to complete.

Output :

Task - 1 -> Task - 2 -> Task - 3

Jerry
  • 1,005
  • 2
  • 13