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?
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.
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.
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.
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.
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")
fsPromises.copyFile
(added in v10.11.0
)
fsPromises.readdir
(added in v10.0
)
fsPromises.mkdir
(added in v10.0
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With