Software Engineering

How to copy files and folders in Node.js? | by Sabesan Sathananthan

Multiple ways to copy files in Node.js

Photo by Dziana Hasanbekava

In Node.js, there are multiple ways to copy files., let’s take a look at the possible ways and analysis each of them. This is my 44th Medium article.

The copyFile() function, which can copy a file directly to the destination directory, performs the simplest action.

fs.copyFile('./data.txt', './dest/info.txt');

The above method, asynchronously copies the file from src to dest. If dest is already exists then by default it is overwritten. There are no args passed to the callback function over than any possible exception. Node.js does not ensure that copy operations are atomic. Node.js will attempt to delete the target file if an error happens after opening the target file for writing.

There is a disadvantage when we use the above method. If the target directory does not exist then an exception will be thrown because the target directory must exist (the method will not automatically create the target directory). Therefore, before using the above method, user must validate whether the target directory definetly exists or not? If the target directory doesn’t exists, user could use fs.mkdir()or fs.mkdirSync()to create the target directory. copyFile() method can’t copy directories.