copyFile() method has the simplest operation and can copy the file directly to the target directory.
Asynchronously copies src to dest. By default, if dest already exists, it is overwritten. No arguments are given to the callback function, except for a possible exception. Node.js does not guarantee the atomicity of the copy operation. If an error occurs after opening the target file for writing, Node.js will try to delete the target file.
However, this method has one disadvantage: the target directory must exist (it does not create directories automatically), and if it does not exist, an exception will be thrown. So when you use copyFile() method, you must make sure that the directory must exist, if not, you need to use
fs.mkdirSync() to create the directory.
Also, copyFile() cannot copy directories.
2. readFile and writeFile
Reads the contents of the src file and then writes it to the target file.
This way is suitable for, if you need to modify the content during the copying process, then write to the target file.
The disadvantage is the same as copyFile() above, writeFile() can only write to files in already existing directories, readFile() is used to read the contents of the file, so it can’t copy directories either.
The advantage is that the contents can be modified during the copying process.
3. createReadStream and createWriteStream
readFile and writeFile manipulate data in whole blocks, which can strain system resources if the file is large. The createReadStream and createWriteStream manipulate data in a stream fashion.
Starting with version 16.7.0, nodejs has a new fs.cp() method that copies the entire directory structure from src to dest asynchronously, including subdirectories and files.
This method can copy both a particular file and a directory. The
recursive property in the configuration needs to be set to true when a directory needs to be copied.
To copy files.
Copy the entire directory, including subdirectories.
As you can see, this method works much better than the previous one:
- there is no more need to make sure that the dest directory must exist, if the dest directory does not exist, it will be created automatically (no matter how many levels of directories).
- you can copy the entire folder, including the subdirectories, without having to do it recursively and separately.
The only thing you need to do is to make sure you have the right version of nodejs!
What if you have a low version of nodejs and you want to copy all the files in the folder? In addition to the linux native cp command in the next section, we can also use the recursive way to copy all the files.
5. cp commands in linux
We can use
spawn in child_process to execute the native commands in linux. The cp command in linux is used to copy files or directories.