alexa

Copy folder in node using cp feature in node.js ?

Copy folder in node using cp feature in node.js ?

Here's a full, self-contained example which creates a sample dir structure, copies it, verifies the copy, and cleans up the sample data:

example.mjs:

 import * as path from 'path';
import {constants as fsConstants, promises as fs} from 'fs';
import {fileURLToPath} from 'url';
import {ok as assert} from 'assert/strict';

// Create sample folder structure, return relative file paths
async function createSampleFiles (rootDir) {
  const writeFileOpts = {encoding: 'utf8'};
  const filePaths = [];

  await fs.mkdir(rootDir, {recursive: true});

  let fPath = 'hello.txt';
  filePaths.push(fPath);
  fPath = path.join(rootDir, fPath);
  let text = 'hello world\n';
  await fs.writeFile(fPath, text, writeFileOpts);

  let dir = 'more';
  await fs.mkdir(path.join(rootDir, dir), {recursive: true});

  fPath = path.join(dir, 'wow.txt');
  filePaths.push(fPath);
  fPath = path.join(rootDir, fPath);
  text = 'wow\n';
  await fs.writeFile(fPath, text, writeFileOpts);

  return filePaths;
}

async function fsEntryExists (filePath) {
  try {
    await fs.access(filePath, fsConstants.F_OK);
    return true;
  }
  catch (ex) {
    if (ex instanceof Error && ex.code === 'ENOENT') return false;
    throw ex;
  }
}

async function assertFSEntryExists (filePath) {
  assert(await fsEntryExists(filePath), `FS entry not found for "${filePath}"`);
}

async function main () {
  const moduleDir = path.dirname(fileURLToPath(import.meta.url));

  const sourceDir = path.join(moduleDir, 'data');
  const destDir = path.join(moduleDir, 'data-copy');

  const relativePaths = await createSampleFiles(sourceDir);

  await fs.cp(sourceDir, destDir, {recursive: true});

  let exitCode = 0;

  try {
    const filePaths = relativePaths.map(fPath => path.join(destDir, fPath));
    for (const fPath of filePaths) await assertFSEntryExists(fPath);
    console.log('Copy successful');
  }
  catch {
    console.error('Copy failed');
    exitCode = 1;
  }
  finally {
    // Cleanup
    for (const dir of [sourceDir, destDir]) {
      if (await fsEntryExists(dir)) await fs.rm(dir, {recursive: true});
    }

    process.exit(exitCode);
  }
}

main(); 
 $ node --version
v16.15.0

$ node example.mjs
Copy successful

208 0
7

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online

Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry