How to use the copy function from fs-extra

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

fs-extra.copy is a method that copies a file or a directory to a new location in a robust way, with additional features over the core fs module.

397
398
399
400
401
402
403
404
405
406
await async.eachSeries(allWorkspaceFiles, async ({ name, localPath, buffer }) => {
  const sourceFile = path.join(sourcePath, name);
  try {
    await fse.ensureDir(path.dirname(sourceFile));
    if (localPath) {
      await fse.copy(localPath, sourceFile);
    } else {
      await fse.writeFile(sourceFile, buffer);
    }
  } catch (err) {
fork icon253
star icon252
watch icon0

258
259
260
261
262
263
264
265
266
267
268
269
  })
    .then(displaySuccessMessage)
}


async function createStarterFiles (installDirectory) {
  await fs.copy(path.join(kitRoot, 'prototype-starter'), installDirectory)


  async function addToConfigFile (key, value) {
    const configFileLocation = path.join(installDirectory, 'app', 'config.json')
    const config = await fs.readJson(configFileLocation)
fork icon234
star icon281
watch icon77

+ 5 other calls in file

How does fs-extra.copy work?

fs-extra.copy is a method provided by the fs-extra library that copies a file or a directory from one location to another while also providing the ability to filter out specific files or directories, preserve file attributes such as timestamps and permissions, and selectively overwrite existing files. Internally, the method first checks whether the source path is a file or a directory and performs the appropriate copy operation using the fs module. If the source path is a directory, the method recursively copies all files and subdirectories to the destination path. Additionally, fs-extra.copy can also handle symbolic links and junctions, and can exclude specific files or directories using filtering options.

347
348
349
350
351
352
353
354
355
356
  renderError('exists')
  return
}

await fse.ensureDir(path.dirname(installLocation))
await fse.copy(templatePath, installLocation)

// Inject a forward slash if the user hasn't included one
if (chosenUrl[0] !== '/') {
  chosenUrl = '/' + chosenUrl
fork icon234
star icon281
watch icon77

+ 2 other calls in file

350
351
352
353
354
355
356
357
358
359
  const fileNames = ['README.md', 'Home.md'];
  const filePath = fileNames.find(fileName => fs.existsSync(path.join(this.rootPath, fileName)));
  // if none of the files exist, do nothing
  if (_.isUndefined(filePath)) return;
  try {
    await fs.copy(path.join(this.rootPath, filePath), indexPagePath);
  } catch (error) {
    throw new Error(`Failed to copy over ${filePath}`);
  }
}
fork icon106
star icon94
watch icon13

+ 21 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
const fse = require("fs-extra");

async function copyFile() {
  try {
    await fse.copy("/path/to/source", "/path/to/destination");
    console.log("File copied successfully!");
  } catch (err) {
    console.error(err);
  }
}

copyFile();

In this example, fs-extra is imported and the copy() method is used to copy the file located at /path/to/source to /path/to/destination. The method returns a promise, which is awaited to ensure that the copy operation is completed before the console logs the success message. If an error occurs during the copy operation, it is caught and logged to the console.

2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
}

try {
    this.lastWriteTimeJobInfo = Date.now();
    await fs.outputFile(CURRENT_INFO_FILE, JSON.stringify(jobInfo, null, 4), 'utf8');
    await fs.copy(CURRENT_INFO_FILE, CURRENT_INFO_FILE + '.bak');
    
    for (var key of nonWriteable) {
        jobInfo[key] = savedData[key];
    }
fork icon82
star icon94
watch icon0

+ 3 other calls in file

93
94
95
96
97
98
99
100
101
102
// move res.neu or resources.neu to app folder
const resources = fs.readdirSync(
  path.resolve(process.cwd(), "dist", appname)
);
const resourcesFile = resources.find((file) => /res(ources)?/.test(file));
await fs.copy(
  path.resolve(process.cwd(), "dist", appname, resourcesFile),
  path.resolve(
    process.cwd(),
    `${appDistributionName}.app`,
fork icon15
star icon187
watch icon0

632
633
634
635
636
637
638
639
640
641
    false,
);

Promise.all([])
    .then(() => fs.remove(fixtureCopyDir))
    .then(() => fs.copy(fixtureDir, fixtureCopyDir))
    .then(() => {
        checkDeps(
            {
                packageDir: `${fixturePrefixSeparate}${fixtureName}-copy`,
fork icon30
star icon115
watch icon0

+ 19 other calls in file

19
20
21
22
23
24
25
26
27
28
  await rimraf(path.join(root, 'core/foo/node_modules'));
  await rimraf(path.join(root, 'core/bar/node_modules'));
  await rimraf(path.join(root, 'core/scoped/node_modules'));
  await rimraf(path.join(root, 'packages/c'));
  await fs.copyFile(path.join(root, 'package-init.json'), path.join(root, 'package.json'));
  await fse.copy(root, tmp);
});

it('should install all on root', async () => {
  await coffee.fork(helper.npminstall, [], { cwd: root })
fork icon64
star icon475
watch icon17

420
421
422
423
424
425
426
427
428
  done: false,
};

if (!(await exports.isInstallDone(targetdir))) {
  await fse.emptyDir(targetdir);
  await fse.copy(src, targetdir);
  await exports.setInstallDone(targetdir);
  result.exists = false;
}
fork icon64
star icon475
watch icon17

566
567
568
569
570
571
572
573
574
575
}

// and copy the common folder from template (contains the default blue node-red icon)
fsOpts.overwrite = false // we don't want to overwrite any common folder files
try {
    fs.copy( path.join( uib.masterTemplateFolder, uib.commonFolderName ), uib.commonFolder, fsOpts, function(err) {
        if (err) {
            log.error(`[uibuilder:runtimeSetup] Error copying common template folder from ${path.join( uib.masterTemplateFolder, uib.commonFolderName)} to ${uib.commonFolder}`, err)
        } else {
            log.trace(`[uibuilder:runtimeSetup] Copied common template folder to local common folder ${uib.commonFolder} (not overwriting)` )
fork icon75
star icon352
watch icon25

+ 12 other calls in file

188
189
190
191
192
193
194
195
196
197
// Does not need setup to have finished running

const fileName = path.join( folder, this.packageJson )

try { // Make a backup copy
    await fs.copy(fileName, `${fileName}.bak`)
    this.log.trace(`[uibuilder:package-mgt:writePackageJson] package.json file successfully backed up in ${folder}`)
} catch (err) {
    this.log.error(`[uibuilder:package-mgt:writePackageJson] Failed to copy package.json to backup.  ${folder}`, this.packageJson, err)
}
fork icon75
star icon346
watch icon24

+ 12 other calls in file

270
271
272
273
274
275
276
277
278
279
const installDirectory = getInstallLocation()

const copyFile = (fileName) => fs.copy(path.join(kitRoot, fileName), path.join(installDirectory, fileName))

await Promise.all([
  fs.copy(path.join(kitRoot, 'prototype-starter'), installDirectory),
  fs.writeFile(path.join(installDirectory, '.gitignore'), gitignore, 'utf8'),
  fs.writeFile(path.join(installDirectory, '.npmrc'), npmrc, 'utf8'),
  copyFile('LICENCE.txt'),
  updatePackageJson(path.join(installDirectory, 'package.json'))
fork icon234
star icon281
watch icon77

+ 29 other calls in file

2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
    if (fs.existsSync(destination)) {
        await fs.removeSync(destination);
    }

    for (const i in jobInfo.multiDeployPaths) {
        await fs.copy(jobInfo.multiDeployPaths[i], destination);
    }

    await this.deployJob(jobInfo);
} else {
fork icon80
star icon94
watch icon26

+ 17 other calls in file

434
435
436
437
438
439
440
441
442
443
const hash = createHash(currBuffer) + createHash(refBuffer);

if (cacheDiffImages.has(hash)) {
    const cachedDiffPath = cacheDiffImages.get(hash);

    await fs.copy(cachedDiffPath, destPath);
    return;
}

await workers.saveDiffTo(imageDiffError, destPath);
fork icon38
star icon39
watch icon5

+ 2 other calls in file

189
190
191
192
193
194
195
196
197
198
199
}


const run = async (dir, sidebar) => {
  for await (const x of walk(dir)) {
    if (x.endsWith('.png') || x.endsWith('.jpeg') || x.endsWith('.jpg')) {
      fs.copy(x, path.resolve('./src/build/assets', path.basename(x)));
    } else if (x.endsWith('.md')) {
      fs.readFile(x, 'utf8', (err, file) => {
        const graymatter = matter(file);
        const frontmatter = graymatter.data;
fork icon11
star icon33
watch icon0

+ 9 other calls in file

144
145
146
147
148
149
150
151
152
153
let target = path.resolve(projectDir, '../temp-test-app-' + uniqueId++)
while (fse.existsSync(target)) {
  target = path.resolve(projectDir, '../temp-test-app-' + uniqueId++)
}
try {
  await fse.copy(projectDir, target)
} catch (error) {
  console.log(error)
  console.log(`recopy`)
  target = copyApp(projectDir)
fork icon11
star icon27
watch icon2

171
172
173
174
175
176
177
178
179
if (!fs.pathExistsSync(paths.shellBuildOutput)) {
    reporter.error('No build output found')
    process.exit(1)
}

await fs.copy(paths.shellBuildOutput, paths.buildAppOutput)

if (packAppOutput) {
    const bundle = path.parse(paths.buildAppBundle)
fork icon12
star icon20
watch icon27

251
252
253
254
255
256
257
258
259
260
await fsExtra.promises.mkdir(path.join(__dirname, 'build/static/js'), {
  recursive: true
});

await Promise.all([
  fsExtra.copy(
    path.join(__dirname, 'static'),
    path.join(__dirname, 'build/static'),
    { overwrite: true, recursive: true }
  ),
fork icon9
star icon18
watch icon0

+ 11 other calls in file

80
81
82
83
84
85
86
87
88
const createCopy = async () => {
  const root = path.resolve(__dirname, '../fixtures');
  const copyDir = path.resolve(__dirname, '..', `test-dir-${Math.random().toString(36).slice(2)}`);

  await fs.ensureDir(copyDir);
  await fs.copy(root, copyDir);

  return copyDir;
};
fork icon7
star icon86
watch icon2

+ 25 other calls in file

288
289
290
291
292
293
294
295
296
297
298
299
        }
    }


    // Copy other needed files
    await fsExtra.copy(path.join(__dirname, '..', 'config.js'), path.join(process.cwd(), 'config.js'));
    await fsExtra.copy(path.join(__dirname, '..', 'source', 'package.json'), path.join(process.cwd(), 'package.json'));
    console.log(chalk.green('[Setup complete]'));
};


const deIndent = (str) => {
fork icon7
star icon46
watch icon3

+ 8 other calls in file

function icon

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