Friday, January 25, 2019

Fs.copyFile(src, dest [, Flags], callback)

The fs.Copyfile module copies the source to the destination asynchronously.

Parameters 

src is the source filename to copy.
dest is the destination filename of the copy.
Flags modifies for copy operation (Optional)
Callback is a <function>

For instance, an error occurs after the dest file has been opened for writing, Node.js would attempt to remove the destination. 

Code example:

constfs =require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('source.txt','destination.txt',(err)=>{
  if(err)throwerr;
  console.log('source.txt was copied to destination.txt');
});

Optional Flag ( If the Flag Argument is an integer)

constfs =require('fs');
const{COPYFILE_EXCL }=fs.constants;

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
fs.copyFile('source.txt','destination.txt',COPYFILE_EXCL,callback);




Fs.copyFileSync(src, dest[, flags])

The fs.CopyfileSync module copies the source to the destination at the same time(Synchronously). The dest is overwritten if it already exists. 

Parameters 
src is the source filename to copy.
dest is the destination filename of the copy.
Flags modifies for copy operation. (Optional

constfs =require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFileSync('source.txt','destination.txt');
console.log('source.txt was copied to destination.txt');

Optional Flag (If the Flag Argument is an integer)

constfs =require('fs');
const{COPYFILE_EXCL }=fs.constants;

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
fs.copyFileSync('source.txt','destination.txt',COPYFILE_EXCL);

The asynchronous method will return a promise if the callback isn't passed.
Whereby the Synchronous method on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.

No comments:

Post a Comment