How to copy contents from one file to another file synchronously in Node.js?

December 16, 2020 - 2 min read

To copy the contents from one file to another file synchronously, we can use the copyFileSync() function from the fs (filesystem) module in Node.js.

// Copy contents from one file to another file
fs.copyFileSync(src, dest);

Let's say we have a file named myFile.txt from which we need to copy the content (called source file) and another file called copyFile.txt where we will have to write the copied contents (called destination file).

First, let's require the fs module and define the source and destination files like this,

// require fs module
const fs = require("fs");

// source to copy content
const src = "myFile.txt";
// destination for copied content
const dest = "copyFile.txt";

To copy the file synchronously we can use the fs.copyFileSync() function and pass the:

  • src as the first argument
  • dest as the second argument

to the function.

It can be done like this,

// require fs module
const fs = require("fs");

// source to copy content
const src = "myFile.txt";
// destination for copied content
const dest = "copyFile.txt";

// use copyFileSync() function
// to copy contents from source file
// and write to destination file synchronously
fs.copyFileSync(src, dest);
  • The destination file will be created even if it doesn't exist in the system and the copied contents will be placed there.

See this example live in repl.it.

Feel free to share if you found this useful 😃.