Copying A File In Node.js v8.5

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.   
  3. 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.   
  3. // Async with promises:  
  4. fs.copy('SourceFile.txt''DestinationFile.txt')  
  5.  .then(() => console.log('success!'))  
  6.  .catch(err => console.error(err));  
Method 2: using callbacks asynchronously
  1. const fs = require('fs-extra');  
  2.   
  3. // Async with callbacks:  
  4. fs.copy('SourceFile.txt''DestinationFile.txt', err => {  
  5.  if (err) return console.error(err)  
  6.  console.log('success!')  
  7. });  
Method 3: Synchronously
  1. const fs = require('fs-extra')  
  2.   
  3. try {  
  4.  fs.copySync('SourceFile.txt''DestinationFile.txt')  
  5.  console.log('success!')  
  6. catch (err) {  
  7.  console.error(err)  
  8. }  
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.   
  3. fs.copyFile('SourceFile.txt''DestinationFile.txt', (err) => {  
  4.     if (err) throw err;  
  5.     console.log('SourceFile.txt was copied to DestinationFile.txt');  
  6. });  
File Copy Synchronously
  1. const fs = require('fs');  
  2.   
  3. fs.copyFileSync('SourceFile.txt''DestinationFile.txt');   


Similar Articles