node

How to copy file in NodeJS


In this article, you are going to learn about how to copy a file in NodeJS.

NodeJS is an open-source JavaScript runtime built on the Chrome V8 engine for executing JavaScript code on the server-side. It is very fast and highly scalable with extensive large community support. You may perform different actions with the help of using NodeJS built-in modules. fs module is one of them. The meaning of fs is a file system that helps you to work with files. such as reading files, writing files, copying files, and so on. In this article, you will see how to copy a file in NodeJS.

In NodeJS, to copy a file all you need to do is to use the fs.copyFile() method. This method comes with the fs module and behaves asynchronously. It mainly copies a file from the source path to the destination path. Let’s see the syntax of using it in NodeJS below:

fs.copyFile( src, dest, mode, callback )

Here, in this method, you can see that it accepts four parameters. The first two is referred to the source and destination both are strings and denote the file path. After that mode is used to determine the copy operation and finally a callback function will be called after the method has been executed successfully and if there is any error then the error message will also be shown in this callback.

Let’s see an example of copying a file in NodeJS to understand things practically. Here, we will copy the content of a test_file.txt to copied_file.txt.

const fs = require('fs');

fs.copyFile('test_file.txt', 'copied_file.txt', (err) => {
  if (err) {
	  console.log('Error Occurred:', err);
  }else {
    console.log('File Copied Successfully!')
  }
});

// Output: File Copied Successfully!

Output

Let’s see our file structure before executing the program.

Here, you can see that there is only one txt file exists with the name of test_file.txt, and this file contains some lorem ispsum text. Let’s execute our code and see if there any changes occurred in the file structure or not.

copy file in NodeJS

Here, you can see that another txt file has been created named copied_file.txt with the same content from test_file.txt. This filename was provided by us in our program and our program executes successfully. This is how you can copy a file by using NodeJS.


Share on social media

//