Node.js Copy a Folder

Node.js Copy a Folder – In this tutorial, we shall learn to copy a folder or directory (containing files and some more folders) to another location using Node fs-extra package with the help of Example Script.

Install Node fs-extra package

To Install Node fs-extra package using NPM (Node Package Manager), run the following command in Terminal.

$ npm install fs-extra

Example – Copy Folder using Node FS Extra

In this example, we will copy a folder “folderA” to folder “folderB” using fs.copy() method.

node-js-copy-a-foder.js

</>
Copy
// include fs-extra package
var fs = require("fs-extra");

var source = 'folderA'
var destination = 'folderB'

// copy source folder to destination
fs.copy(source, destination, function (err) {
	if (err){
		console.log('An error occured while copying the folder.')
		return console.error(err)
	}
	console.log('Copy completed!')
});

Open a terminal or command prompt and run this script using node command as shown in the following.

Output

arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node node-js-copy-a-foder.js
Copy completed!

Conclusion

In this Node.js Tutorial – Node FS – Node.js Copy a Folder, we have learnt to install Node fs-extra package and to copy a folder or directory (containing files and some more folders) to another location using Node fs-extra package with the help of an Example Script.