UNPKG

2.41 kBMarkdownView Raw
1# copy(src, dest, [options, callback])
2
3Copy a file or directory. The directory can have contents. Like `cp -r`.
4
5- `src` `<String>` Note that if `src` is a directory it will copy everything inside of this directory, not the entire directory itself (see [issue #537](https://github.com/jprichardson/node-fs-extra/issues/537)).
6- `dest` `<String>` Note that if `src` is a file, `dest` cannot be a directory (see [issue #323](https://github.com/jprichardson/node-fs-extra/issues/323)).
7- `options` `<Object>`
8 - `overwrite` `<boolean>`: overwrite existing file or directory, default is `true`. _Note that the copy operation will silently fail if you set this to `false` and the destination exists._ Use the `errorOnExist` option to change this behavior.
9 - `errorOnExist` `<boolean>`: when `overwrite` is `false` and the destination exists, throw an error. Default is `false`.
10 - `dereference` `<boolean>`: dereference symlinks, default is `false`.
11 - `preserveTimestamps` `<boolean>`: When true, will set last modification and access times to the ones of the original source files. When false, timestamp behavior is OS-dependent. Default is `false`.
12 - `filter` `<Function>`: Function to filter copied files. Return `true` to include, `false` to exclude. Can also return a `Promise` that resolves to `true` or `false` (or pass in an `async` function).
13- `callback` `<Function>`
14
15## Example:
16
17```js
18const fs = require('fs-extra')
19
20// With a callback:
21fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
22 if (err) return console.error(err)
23
24 console.log('success!')
25}) // copies file
26
27fs.copy('/tmp/mydir', '/tmp/mynewdir', err => {
28 if (err) return console.error(err)
29
30 console.log('success!')
31}) // copies directory, even if it has subdirectories or files
32
33// With Promises:
34fs.copy('/tmp/myfile', '/tmp/mynewfile')
35.then(() => {
36 console.log('success!')
37})
38.catch(err => {
39 console.error(err)
40})
41
42// With async/await:
43async function example () {
44 try {
45 await fs.copy('/tmp/myfile', '/tmp/mynewfile')
46 console.log('success!')
47 } catch (err) {
48 console.error(err)
49 }
50}
51
52example()
53```
54
55**Using filter function**
56
57```js
58const fs = require('fs-extra')
59
60const filterFunc = (src, dest) => {
61 // your logic here
62 // it will be copied if return true
63}
64
65fs.copy('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }, err => {
66 if (err) return console.error(err)
67
68 console.log('success!')
69})
70```