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?
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
<sup>(added inv10.11.0
)</sup>fsPromises.readdir
<sup>(added inv10.0
)</sup>fsPromises.mkdir
<sup>(added inv10.0
)</sup>