Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node fs copy a folder

Tags:

I am trying to copy a folder using Node fs module. I am familiar with readFileSync() and writeFileSync() methods but I am wondering what method I should use to copy a specified folder?

like image 926
y. lu Avatar asked Aug 23 '16 16:08

y. lu


People also ask

How do I copy a directory in fs?

To copy a folder recursively in Node. js, we can use the copySync method from the fs-extra module. const fse = require('fs-extra'); const srcDir = `path/to/file`; const destDir = `path/to/destination/directory`; fse. copySync(srcDir, destDir, { overwrite: true }, (err) => { if (err) { console.

How do I copy files from one directory to another in node JS?

The fs. copyFile() method is used to asynchronously copy a file from the source path to destination path. By default, Node. js will overwrite the file if it already exists at the given destination.

How do you copy a folder in Windows Terminal?

Type "xcopy", "source", "destination" /t /e in the Command Prompt window. Instead of “ source ,” type the path of the folder hierarchy you want to copy. Instead of “ destination ,” enter the path where you want to store the copied folder structure. Press “Enter” on your keyboard.


2 Answers

You can use fs-extra to copy contents of one folder to another like this

var fs = require("fs-extra");

fs.copy('/path/to/source', '/path/to/destination', function (err) {
  if (err) return console.error(err)
  console.log('success!')
});

There's also a synchronous version.

like image 160
user3248186 Avatar answered Sep 28 '22 20:09

user3248186


Save yourself the extra dependency with just 10 lines of native node functions

Add the following copyDir function:

const { promises: fs } = require("fs")
const path = require("path")

async function copyDir(src, dest) {
    await fs.mkdir(dest, { recursive: true });
    let entries = await fs.readdir(src, { withFileTypes: true });

    for (let entry of entries) {
        let srcPath = path.join(src, entry.name);
        let destPath = path.join(dest, entry.name);

        entry.isDirectory() ?
            await copyDir(srcPath, destPath) :
            await fs.copyFile(srcPath, destPath);
    }
}

And then use like this:

copyDir("./inputFolder", "./outputFolder")

Further Reading

  • Copy folder recursively in node.js
  • fsPromises.copyFile (added in v10.11.0)
  • fsPromises.readdir (added in v10.0)
  • fsPromises.mkdir (added in v10.0)
like image 37
KyleMit Avatar answered Sep 28 '22 20:09

KyleMit