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.
- const fs = require('fs');
-
- 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.
- npm install --save fs-extra
Now, you can use
fs-extra like the following ways.
Method 1: using promises
- const fs = require('fs-extra');
-
-
- fs.copy('SourceFile.txt', 'DestinationFile.txt')
- .then(() => console.log('success!'))
- .catch(err => console.error(err));
Method 2: using callbacks asynchronously
- const fs = require('fs-extra');
-
-
- fs.copy('SourceFile.txt', 'DestinationFile.txt', err => {
- if (err) return console.error(err)
- console.log('success!')
- });
Method 3: Synchronously
- const fs = require('fs-extra')
-
- try {
- fs.copySync('SourceFile.txt', 'DestinationFile.txt')
- console.log('success!')
- } catch (err) {
- console.error(err)
- }
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
- const fs = require('fs');
-
- fs.copyFile('SourceFile.txt', 'DestinationFile.txt', (err) => {
- if (err) throw err;
- console.log('SourceFile.txt was copied to DestinationFile.txt');
- });
File Copy Synchronously
- const fs = require('fs');
-
- fs.copyFileSync('SourceFile.txt', 'DestinationFile.txt');