How to use the copySync function from fs-extra

Find comprehensive JavaScript fs-extra.copySync code examples handpicked from public code repositorys.

fs-extra.copySync is a function in Node.js that copies a file or directory from a source path to a destination path synchronously, with support for advanced options like filtering and preserving timestamps.

306
307
308
309
310
311
312
313
314

// Clear all files from previous staging runs
fs.removeSync(crxPath);

// Copy crx files to tmp staging directory
fs.copySync(path.join(__dirname, '../../assets/crx'), crxPath)

// Load extension manifest and default icon
yield crx.load(crxPath);
fork icon86
star icon477
watch icon0

218
219
220
221
222
223
224
225
226
227
function _copyExamples() {
  if (!_opts.skipExamples) {
    log(chalk.yellow('Copying examples folder...'));
    fsExtra.mkdirSync(`${_exampleBuild}/components`);
    fsExtra.copySync(`${_testScriptFolder}/examples-scaffold`, `${_exampleBuild}`);
    fsExtra.copySync(_exampleSrc, `${_exampleBuild}/components`);
    _examples = _getDirectories(`${_exampleBuild}/components`);
  }
}

fork icon114
star icon127
watch icon0

How does fs-extra.copySync work?

fs-extra.copySync is a function provided by the fs-extra library in Node.js used to copy a file or directory from a source path to a destination path synchronously. When fs-extra.copySync is called, it takes as input a source path, a destination path, and an optional options object containing advanced options like filtering and preserving timestamps. The function recursively copies all files and subdirectories from the source path to the destination path, creating any necessary directories along the way. By default, copySync overwrites existing files at the destination path. The options object can be used to modify the behavior of copySync. For example, you can set the filter option to a function that filters which files and directories to include in the copy. You can also set the preserveTimestamps option to true to preserve the file modification times of the original files. fs-extra.copySync is a synchronous function, meaning that it blocks the main thread until the copy operation is complete. If you need to copy large files or directories, you may want to use the asynchronous version of this function, fs-extra.copy, which uses callbacks or promises to handle completion and errors. fs-extra.copySync is commonly used in Node.js applications to copy files or directories, such as during deployment or backup procedures. By providing advanced options for filtering and preserving timestamps, copySync can be customized to suit a wide variety of use cases.

1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
 * Copies core-web bundles and external assets to the assets output folder
 */
copyCoreWebAsset() {
  const coreWebRootPath = path.dirname(require.resolve('@markbind/core-web/package.json'));
  const coreWebAssetPath = path.join(coreWebRootPath, 'asset');
  fs.copySync(coreWebAssetPath, this.siteAssetsDestPath);

  const dirsToCopy = ['fonts'];
  const filesToCopy = [
    'js/markbind.min.js',
fork icon106
star icon94
watch icon13

2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
errorLog += 'Errors:' + (jobInfo.errors && jobInfo.errors.length > 0 ? ('\n' + jobInfo.errors.join('\n')) : ' None');

try {
    if (forceWrite || !this.lastWriteTimeLog || (Date.now() - this.lastWriteTimeLog > 60000)) {
        fs.outputFileSync('VlocityBuildLog.yaml', yaml.dump(logInfo, { lineWidth: 1000 }));
        fs.copySync('VlocityBuildLog.yaml', path.join(this.vlocity.tempFolder, 'logs', jobInfo.logName));
        fs.outputFileSync('VlocityBuildErrors.log', errorLog);
        this.lastWriteTimeLog = Date.now();
    }
} catch (e) {
fork icon82
star icon94
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
const fs = require("fs-extra");

// Copy a file
fs.copySync("source/file.txt", "destination/file.txt");

// Copy a directory
fs.copySync("source/directory", "destination/directory");

In this example, we first import the fs-extra library. We then call fs.copySync twice to copy a file and a directory from a source path to a destination path. The first call to copySync copies a file called file.txt from the source directory to the destination directory, creating the destination directory if it doesn't exist. The second call to copySync copies a directory called directory from the source directory to the destination directory, recursively copying all files and subdirectories inside. When copySync is called, it blocks the main thread until the copy operation is complete. If there are any errors during the copy operation, an exception will be thrown. fs-extra.copySync is a powerful and flexible function that can be used to copy files or directories in a wide variety of use cases.

320
321
322
323
324
325
326
327
328
329
  return s;
}

async cloneDir(source_path, target_path) {
  if (this.getNodeIsWindows()) {
    fse.copySync(
      this.stripTrailingSlash(source_path),
      this.stripTrailingSlash(target_path),
      {
        overwrite: true,
fork icon55
star icon500
watch icon0

1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
// Destination depends on whether we are
// copying a directory or a file
if (fs.lstatSync(path).isDirectory()) {
  fs.copySync(path, destinationFolderPath)
} else {
  fs.copySync(path, destinationFolderPath +
                    fsPath.basename(path))
}

console.log('Copied ' + path + ' to epub folder.')
fork icon39
star icon105
watch icon0

+ 7 other calls in file

40
41
42
43
44
45
46
47
48
49
} else {
  filePath = `../${projectName}/reports/testReport-${date}.html`;
}

const file = filePath;
await fs.copySync(tempFile, file);

/**
 * list of browsers test running on via lambdatest
 * @type {string[]}
fork icon29
star icon40
watch icon4

+ 8 other calls in file

7
8
9
10
11
12
13
14
15
16
const rmFileAsync = promisify(fs.unlink);
const copyFileAsync = promisify(fs.copyFile);
const rmDirAsync = promisify(fs.rmdir);
const accessAsync = promisify(fs.access);
const writeFileSync = fs.writeFileSync;
const copyDirSync = fse.copySync

const fileExistsAsync = async (filePath: string) => {
  try {
    await accessAsync(filePath, fs.F_OK);
fork icon4
star icon26
watch icon8

54
55
56
57
58
59
60
61
62
63
            if (dstChmodError.code !== "ENOENT") {
                throw dstChmodError
            }
        }
    }
    fs.copySync(source, output)
}
fs.chmodSync(output, stat.mode)

if (options.preserve) {
fork icon3
star icon28
watch icon0

1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360


if (process.platform === "linux") {
  //check if data exists inside of the Soda folder, and if it does, move it into the capitalized SODA folder
  if (fs.existsSync(path.join(homeDirectory, "Soda"))) {
    //copy the folder contents of home/Soda to home/SODA
    fs.copySync(path.join(homeDirectory, "Soda"), path.join(homeDirectory, "SODA"));
    //delete the old folder
    fs.removeSync(path.join(homeDirectory, "Soda"));
  }
}
fork icon9
star icon22
watch icon9

+ 9 other calls in file

26
27
28
29
30
31
32
33
34
35
36
    console.log("make directory: " + argv.name + "/test");
    util.makeDir(argv.name + "/test");


    console.log("make directory: " + argv.name + "/libjs");
    libDir = __dirname + "/./libjs";
    fse.copySync(libDir, argv.name + "/libjs");


    return;
};
fork icon6
star icon19
watch icon8

133
134
135
136
137
138
139
140
141
142
// Create target directory
fs.ensureDirSync(targetDir, 0o2755);

// Copy file
console.log(`Copying ${fileName} from ${sourceDir}/ to ${targetDir}/...`);
fs.copySync(`${sourceDir}/${fileName}`, `${targetDir}/${fileName}`);

// Set permissions
if (userId && groupId) {
  // Set every folder to path permissions
fork icon3
star icon12
watch icon0

207
208
209
210
211
212
213
214
215
216
217
    });
  });
}


function copyPublicFolder() {
  fs.copySync(paths.appPublic, paths.appBuild, {
    dereference: true,
    filter: file => file !== paths.appHtml,
  });
}
fork icon1
star icon6
watch icon0

656
657
658
659
660
661
662
663
664
}else if(req.body.backupName){
    fileName = req.body.backupName;
    if(fs.existsSync(path.join(backendDir, "tmp", fileName))){
        await fs.rm(path.join(backendDir, "tmp", fileName));
    }
    fs.copySync(path.join(backendDir, "backup", "settings", fileName), path.join(backendDir, "tmp", fileName), {overwrite:true});
}

let fileDir = path.join(backendDir, "tmp", fileName.split(".")[0]);
fork icon3
star icon30
watch icon0

+ 11 other calls in file

4
5
6
7
8
9
10
11
12
13
14
15


gulp.task('init', function () {
  console.log('Initializing your project');


  try {
    fs.copySync('./templates/app.template.js', './src/app.js');
  } catch(e) {
    console.error('Could not copy the app.js file. You may have to manually copy and rename templates/app.template.js to src/app.js');
    console.error(e);
  }
fork icon3
star icon26
watch icon4

+ 3 other calls in file

110
111
112
113
114
115
116
117
118
119
);
const targetPath = path.resolve(process.cwd(), this.projectName);
try {
  fse.ensureDirSync(templatePath);
  fse.ensureDirSync(targetPath);
  fse.copySync(templatePath, targetPath);
  spinner.stop(true);
  log.success('模板安装成功');
} catch (e) {
  log.success('模板安装失败');
fork icon0
star icon2
watch icon0

211
212
213
214
215
216
217
218
219
220
    JSON.stringify(packageJson, null, 2) + os.EOL
);

const templateDir = path.join(templatePath, "template");
if (fs.existsSync(templateDir)) {
    fs.copySync(templateDir, root);
} else {
    console.error(
        `Could not locate supplied template: ${chalk.green(templateDir)}`
    );
fork icon1
star icon1
watch icon1

324
325
326
327
328
329
330
331
332
333
    'https://registry.yarnpkg.com';
} catch (e) {
  // ignore
}
if (yarnUsesDefaultRegistry) {
  fs.copySync(
    require.resolve('./yarn.lock.cached'),
    path.join(root, 'yarn.lock')
  );
}
fork icon1
star icon0
watch icon2

+ 4 other calls in file

236
237
238
239
240
241
242
243
244
245
}

// Copy the files for the user
const templateDir = path.join(templatePath, 'template');
if (fs.existsSync(templateDir)) {
  fs.copySync(templateDir, appPath);
} else {
  console.error(
    `Could not locate supplied template: ${chalk.green(templateDir)}`
  );
fork icon1
star icon0
watch icon2

+ 4 other calls in file

257
258
259
260
261
262
263
264
265
266
            // fine without special permissions, but fall back on copying in the unlikely
            // event that fails, too.
            try {
                fse.ensureSymlinkSync(src, dest, type);
            } catch (e) {
                fse.copySync(src, dest);
            }
        });
}

fork icon1
star icon0
watch icon0

+ 3 other calls in file

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)