Introduction
In this article, I am going to explain different ways to copy a file in node.js and will talk about copy function that is newly implemented in the brand new Node.js version 8.5.
Example 1
This is a good way to copy a file in node.js via a single line of code.
  1. const fs = require('fs');
  2. fs.createReadStream('SourceFile.txt').pipe(fs.createWriteStream('DestinationFile.txt'));
Example 2
Some people also use "fs-extra" package to use the extra functions for file management.
what is fs-extra?
According to fs-extra definition, fs-extra adds file system methods that aren't included in the native fs module and adds the Promise Support to the fs methods. It should be a drop-in replacement for fs.
You can download fs-extra like below.
  1. npm install --save fs-extra
Now, you can use fs-extra like the following ways.
Method 1: using promises
  1. const fs = require('fs-extra');
  2. // Async with promises:
  3. fs.copy('SourceFile.txt', 'DestinationFile.txt')
  4. .then(() => console.log('success!'))
  5. .catch(err => console.error(err));
Method 2: using callbacks asynchronously
  1. const fs = require('fs-extra');
  2. // Async with callbacks:
  3. fs.copy('SourceFile.txt', 'DestinationFile.txt', err => {
  4. if (err) return console.error(err)
  5. console.log('success!')
  6. });
Method 3: Synchronously
  1. const fs = require('fs-extra')
  2. try {
  3. fs.copySync('SourceFile.txt', 'DestinationFile.txt')
  4. console.log('success!')
  5. } catch (err) {
  6. console.error(err)
  7. }
And, there are a lot of ways to copy a file in node.js
File copy with the core fs module in 8.5.0

With Node.js 8.5, a new File System feature is shipped by which you can copy the files using the core fs module.
File Copy Asynchronously
  1. const fs = require('fs');
  2. fs.copyFile('SourceFile.txt', 'DestinationFile.txt', (err) => {
  3. if (err) throw err;
  4. console.log('SourceFile.txt was copied to DestinationFile.txt');
  5. });
File Copy Synchronously
  1. const fs = require('fs');
  2. fs.copyFileSync('SourceFile.txt', 'DestinationFile.txt');