# Sync Copy in fs-extra using NodeJS

Node.jsServer Side ProgrammingProgramming

## Introduction to Sync copy

This method copies files or directories from one location to another location in a sync process. The directory can have sub-directories and files.

## Syntax

copySync(src, dest[, options])

## Parameters

• src – This is a string paramter which will hold the source location of the file or directory that needs to be copies. If the location is a directory, it will copy everything inside of the directory instead of whole directory.

• dest – This will hold the destination location where the files/directories will be copies. If src is a files, dest cannot be a directory.

## Options

• overwrite – If set to true, existing files or directories will be overwritten. Default value is set to true.

• errorOnExist – It will throw an error if the destination file/folder exists only when overwrite is set to false.

• preserveTimestamps – Latest modification and access time will be set to that of the original files if true, else it will be OS dependent.

• filter – This option will filter copied files. Will include filtered files if set to true.

Since it is a sync copy, it will not have a callback.

## Example 1

• Check that fs-extra is installed before proceeding; if not, install fs-exra.

• You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
• Create a syncCopyExample.js and copy-paste the following code snippet into that file.

• Now, run the following command to run the following code snippet.

node syncCopyExample.js

Code Snippet

const fs = require('fs-extra')

// copying file in sync process
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log("File copied in Sync")

// Copies directory from src to dest
fs.copySync('/tmp/mydir', '/tmp/mynewdir')
console.log("Directory copied in Sync")

## Output

C:\Users\tutorialsPoint\> node syncCopyExample.js
File copied in Sync
Directory copied in Sync

## Example 2 (Using filter function)

const fs = require('fs-extra')

// Copying files with .txt or .avi as extension
fs.copySync(
'/tmp/newFile.txt', '/tmp/myfile2.txt',  /.*(.txt|.avi)\$/,
(err) => { console.log ('An error occured while copying')})
console.log("Successfully copied !")

C:\Users\tutorialsPoint\> node syncCopyExample.js
Successfully copied!
Published on 28-Apr-2021 06:57:27