Search code examples
javascriptnode.jsfs

Copy folder recursively in Node.js


Is there an easier way to copy a folder and all its content without manually doing a sequence of fs.readir, fs.readfile, fs.writefile recursively?

I am just wondering if I'm missing a function which would ideally work like this:

fs.copy("/path/to/source/folder", "/path/to/destination/folder");

Regarding this historic question. Note that fs.cp and fs.cpSync can copy folders recursively and are available in Node v16+


Solution

  • Since Node v16.7.0 it is possible to use fs.cp or fs.cpSync function.

    fs.cp(src, dest, {recursive: true}, (err) => {/* callback */});
    // Or
    fs.cpSync(src, dest, {recursive: true});
    

    Current stability (in Node v21.1.0) is Experimental.
    It is no longer experimental as of v22.3.0.