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) {
GitHub: alphagov/govuk-prototype-kit
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)
+ 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
+ 2 other calls in file
GitHub: MarkBind/markbind
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}`); } }
+ 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]; }
+ 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`,
GitHub: mgol/check-dependencies
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`,
+ 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 })
GitHub: cnpm/npminstall
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; }
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)` )
+ 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) }
+ 12 other calls in file
GitHub: alphagov/govuk-prototype-kit
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'))
+ 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 {
+ 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);
+ 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;
+ 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)
GitHub: dhis2/app-platform
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)
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 } ),
+ 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; };
+ 25 other calls in file
GitHub: mrvautin/squido
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) => {
+ 8 other calls in file
fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)