← Complete Projects

阅读中文版本

Build a One-Way Directory Sync Tool

A command-line tool that mirrors a source directory into a target by copying new and changed files, deleting extras in the target, and reporting every action, with a dry-run mode.

beginner~4 hnodejsclifilesystemsync

Project goal

Build a CLI that compares a source and target directory tree and makes the target match the source by copying, updating, and deleting files, with a dry-run preview and a summary of actions.

Final features

  • Compare two directory trees by relative path and modification time.
  • Copy new files and overwrite changed files in the target.
  • Delete files present in the target but absent from the source.
  • Support a dry-run mode that reports actions without changing anything.
  • Never follow symbolic links out of the source tree.

Architecture

A scanner builds two path-to-metadata maps; a planner diffs the maps into a list of copy, update, and delete actions; an executor applies the plan; and a reporter prints the plan. The planner is pure so it can be tested against fabricated metadata without touching disk.

Prerequisites

  • Node.js 20 LTS or later
  • Understanding of file metadata and relative paths
  • Familiarity with recursive directory traversal

Dependencies

  • node >=20 — File system traversal, copying, and the CLI entry point
  • vitest ^2.1.0 — Planner tests over fabricated trees

Directory structure

dir-sync/
├── src/
│   ├── scan.js
│   ├── plan.js
│   ├── execute.js
│   ├── report.js
│   └── cli.js
├── test/
│   ├── plan.test.js
│   └── cli.test.js
└── package.json

Phases

1. Tree scanner

Walk a directory and build a map of relative path to size and modification time without following out-of-tree links.

Files: src/scan.js

import { readdir, lstat } from 'node:fs/promises';
import { join, relative } from 'node:path';

export async function scan(root) {
  const map = new Map();
  async function walk(dir) {
    for (const entry of await readdir(dir, { withFileTypes: true })) {
      const full = join(dir, entry.name);
      if (entry.isSymbolicLink()) continue;
      if (entry.isDirectory()) await walk(full);
      else {
        const info = await lstat(full);
        map.set(relative(root, full).replace(/\\/g, '/'), {
          size: info.size,
          mtimeMs: info.mtimeMs,
        });
      }
    }
  }
  await walk(root);
  return map;
}

Expected behavior: Scanning a nested tree returns relative paths with sizes and times, and a symbolic link is skipped rather than followed.

2. Sync planner

Diff the source and target maps into a sorted list of copy, update, and delete actions.

Files: src/plan.js

export function planSync(source, target) {
  const actions = [];
  for (const [rel, meta] of source) {
    const existing = target.get(rel);
    if (!existing) actions.push({ type: 'copy', rel });
    else if (meta.mtimeMs > existing.mtimeMs || meta.size !== existing.size) {
      actions.push({ type: 'update', rel });
    }
  }
  for (const rel of target.keys()) if (!source.has(rel)) actions.push({ type: 'delete', rel });
  return actions.sort((a, b) => a.rel.localeCompare(b.rel));
}

Expected behavior: A source with one new and one changed file and a target with one extra file yields exactly one copy, one update, and one delete.

3. Executor

Apply the plan by copying files with directory creation and deleting extras, creating every parent directory first.

Files: src/execute.js

import { mkdir, copyFile, rm } from 'node:fs/promises';
import { dirname, join } from 'node:path';

export async function execute(actions, { source, target }) {
  const done = [];
  for (const action of actions) {
    const from = join(source, action.rel);
    const to = join(target, action.rel);
    if (action.type === 'delete') await rm(to, { force: true });
    else {
      await mkdir(dirname(to), { recursive: true });
      await copyFile(from, to);
    }
    done.push(action);
  }
  return done;
}

Expected behavior: After execution the target contains exactly the source files, and a deleted file is gone from the target.

4. Reporter

Print a readable summary of the plan and a final count of copied, updated, and deleted files.

Files: src/report.js

const VERB = { copy: '+', update: '~', delete: '-' };

export function formatPlan(actions) {
  if (actions.length === 0) return 'already in sync';
  return actions.map((a) => VERB[a.type] + ' ' + a.rel).join('\n');
}

export function summarize(actions) {
  const counts = { copy: 0, update: 0, delete: 0 };
  for (const a of actions) counts[a.type]++;
  return counts;
}

Expected behavior: An empty plan prints already in sync, and a populated plan prints one prefixed line per action with correct counts.

5. CLI surface

Parse source, target, and flags, run a dry run by default when asked, and refuse to run if the target is inside the source.

Files: src/cli.js

import { scan } from './scan.js';
import { planSync } from './plan.js';
import { execute } from './execute.js';
import { formatPlan, summarize } from './report.js';

const args = parse(process.argv.slice(2));
if (!args.source || !args.target) {
  console.error('usage: sync --source <dir> --target <dir> [--dry-run]');
  process.exit(1);
}
if (args.target.startsWith(args.source)) {
  console.error('refusing: target is inside source');
  process.exit(1);
}
const plan = planSync(await scan(args.source), await scan(args.target));
console.log(formatPlan(plan));
if (!args.dryRun) {
  await execute(plan, { source: args.source, target: args.target });
  console.log(JSON.stringify(summarize(plan)));
}

Expected behavior: A dry run prints the plan and changes nothing, a real run applies it, and a target nested in the source exits with code 1.

6. Tests and hardening

Cover the planner with fabricated trees and the CLI with temporary directories, then fix failures.

Files: test/plan.test.js

import { planSync } from '../src/plan.js';

test('new, changed, and extra files produce one action each', () => {
  const source = new Map([
    ['keep.txt', { size: 10, mtimeMs: 200 }],
    ['new.txt', { size: 5, mtimeMs: 100 }],
  ]);
  const target = new Map([
    ['keep.txt', { size: 9, mtimeMs: 100 }],
    ['extra.txt', { size: 3, mtimeMs: 100 }],
  ]);
  expect(planSync(source, target)).toEqual([
    { type: 'update', rel: 'keep.txt' },
    { type: 'copy', rel: 'new.txt' },
    { type: 'delete', rel: 'extra.txt' },
  ]);
});

Expected behavior: The planner suite passes, and an integration test confirms the target mirrors the source after a real run.

Testing

Run npx vitest. Planner tests construct in-memory maps for cases like a new file, a changed file, and an extra target file, and assert the exact action list. An integration test builds two temporary trees, runs the sync, and asserts the target now mirrors the source file for file, including a deletion.

Troubleshooting

The tool deletes everything in the target

Guard against a target inside the source and require both paths to exist; a typo that points the target at an empty directory should be caught before any deletion runs.

Unchanged files are copied every run

Compare both size and modification time and treat an equal size with an older-or-equal mtime as unchanged; copying on mtime alone makes a fresh checkout look different from its source.

Symbolic links cause infinite recursion

Skip symbolic links entirely during scanning, or track visited real paths; following links out of the tree is both slow and a path-traversal risk.

Deployment

Run from a scheduled job or a deploy script, always with a dry run first in production. Because the plan is deterministic, a dry run in CI can assert the expected change set before the real run applies it.

Known limitations

  • Comparison trusts modification time and size rather than content hashes, so a regenerated file with the same size may be skipped.
  • Sync is one-way only; running it in both directions would need conflict rules this project does not define.

Project overview

A sync tool is a lesson in planning before acting. Computing the full set of changes first makes the operation reviewable, lets a dry run preview it, and keeps the executor a simple loop over a pure plan.

This project mirrors one directory into another, copies and updates changed files, removes extras, and prints exactly what it intends to do before it does it.

The planner is pure and total: given two trees it returns the complete list of actions, which is what makes dry-run and execution share one code path:

export function planSync(source, target) {
  const actions = [];
  for (const [rel, meta] of source) {
    const existing = target.get(rel);
    if (!existing) actions.push({ type: 'copy', rel, size: meta.size });
    else if (meta.mtimeMs > existing.mtimeMs || meta.size !== existing.size) {
      actions.push({ type: 'update', rel, size: meta.size });
    }
  }
  for (const rel of target.keys()) {
    if (!source.has(rel)) actions.push({ type: 'delete', rel });
  }
  return actions.sort((a, b) => a.rel.localeCompare(b.rel));
}

Because the plan is sorted and pure, the same function backs the dry run and the real run, so what the preview shows is what will happen.

Setup

No runtime dependencies are required; scanning, copying, and comparing all use the standard library.

Dependency Version Why it is here
node >=20 File system traversal, copying, and the CLI entry point
vitest ^2.1.0 Planner tests over fabricated trees

Create the project and install:

mkdir dir-sync && cd dir-sync
npm init -y
npm install -D vitest@^2.1.0

Wire the CLI and tests in package.json:

{
  "name": "dir-sync",
  "type": "module",
  "scripts": {
    "sync": "node src/cli.js",
    "test": "vitest run"
  }
}

Tests build temporary trees with mkdtemp so they never depend on or pollute a real directory.

Phase 1: Tree scanner

Walk a directory and build a map of relative path to size and modification time without following out-of-tree links. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.

import { readdir, lstat } from 'node:fs/promises';
import { join, relative } from 'node:path';

export async function scan(root) {
  const map = new Map();
  async function walk(dir) {
    for (const entry of await readdir(dir, { withFileTypes: true })) {
      const full = join(dir, entry.name);
      if (entry.isSymbolicLink()) continue;
      if (entry.isDirectory()) await walk(full);
      else {
        const info = await lstat(full);
        map.set(relative(root, full).replace(/\\/g, '/'), {
          size: info.size,
          mtimeMs: info.mtimeMs,
        });
      }
    }
  }
  await walk(root);
  return map;
}

Acceptance for this phase: Scanning a nested tree returns relative paths with sizes and times, and a symbolic link is skipped rather than followed.

Phase 2: Sync planner

Diff the source and target maps into a sorted list of copy, update, and delete actions. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.

export function planSync(source, target) {
  const actions = [];
  for (const [rel, meta] of source) {
    const existing = target.get(rel);
    if (!existing) actions.push({ type: 'copy', rel });
    else if (meta.mtimeMs > existing.mtimeMs || meta.size !== existing.size) {
      actions.push({ type: 'update', rel });
    }
  }
  for (const rel of target.keys()) if (!source.has(rel)) actions.push({ type: 'delete', rel });
  return actions.sort((a, b) => a.rel.localeCompare(b.rel));
}

Acceptance for this phase: A source with one new and one changed file and a target with one extra file yields exactly one copy, one update, and one delete.

Phase 3: Executor

Apply the plan by copying files with directory creation and deleting extras, creating every parent directory first. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.

import { mkdir, copyFile, rm } from 'node:fs/promises';
import { dirname, join } from 'node:path';

export async function execute(actions, { source, target }) {
  const done = [];
  for (const action of actions) {
    const from = join(source, action.rel);
    const to = join(target, action.rel);
    if (action.type === 'delete') await rm(to, { force: true });
    else {
      await mkdir(dirname(to), { recursive: true });
      await copyFile(from, to);
    }
    done.push(action);
  }
  return done;
}

Acceptance for this phase: After execution the target contains exactly the source files, and a deleted file is gone from the target.

Phase 4: Reporter

Print a readable summary of the plan and a final count of copied, updated, and deleted files. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.

const VERB = { copy: '+', update: '~', delete: '-' };

export function formatPlan(actions) {
  if (actions.length === 0) return 'already in sync';
  return actions.map((a) => VERB[a.type] + ' ' + a.rel).join('\n');
}

export function summarize(actions) {
  const counts = { copy: 0, update: 0, delete: 0 };
  for (const a of actions) counts[a.type]++;
  return counts;
}

Acceptance for this phase: An empty plan prints already in sync, and a populated plan prints one prefixed line per action with correct counts.

Phase 5: CLI surface

Parse source, target, and flags, run a dry run by default when asked, and refuse to run if the target is inside the source. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.

import { scan } from './scan.js';
import { planSync } from './plan.js';
import { execute } from './execute.js';
import { formatPlan, summarize } from './report.js';

const args = parse(process.argv.slice(2));
if (!args.source || !args.target) {
  console.error('usage: sync --source <dir> --target <dir> [--dry-run]');
  process.exit(1);
}
if (args.target.startsWith(args.source)) {
  console.error('refusing: target is inside source');
  process.exit(1);
}
const plan = planSync(await scan(args.source), await scan(args.target));
console.log(formatPlan(plan));
if (!args.dryRun) {
  await execute(plan, { source: args.source, target: args.target });
  console.log(JSON.stringify(summarize(plan)));
}

Acceptance for this phase: A dry run prints the plan and changes nothing, a real run applies it, and a target nested in the source exits with code 1.

Phase 6: Tests and hardening

Cover the planner with fabricated trees and the CLI with temporary directories, then fix failures. Because the phase is complete on its own, the tutorial can be paused and resumed at its boundaries without losing the thread.

import { planSync } from '../src/plan.js';

test('new, changed, and extra files produce one action each', () => {
  const source = new Map([
    ['keep.txt', { size: 10, mtimeMs: 200 }],
    ['new.txt', { size: 5, mtimeMs: 100 }],
  ]);
  const target = new Map([
    ['keep.txt', { size: 9, mtimeMs: 100 }],
    ['extra.txt', { size: 3, mtimeMs: 100 }],
  ]);
  expect(planSync(source, target)).toEqual([
    { type: 'update', rel: 'keep.txt' },
    { type: 'copy', rel: 'new.txt' },
    { type: 'delete', rel: 'extra.txt' },
  ]);
});

Acceptance for this phase: The planner suite passes, and an integration test confirms the target mirrors the source after a real run.

Testing strategy

Run npx vitest. Planner tests construct in-memory maps for cases like a new file, a changed file, and an extra target file, and assert the exact action list. An integration test builds two temporary trees, runs the sync, and asserts the target now mirrors the source file for file, including a deletion.

The dry-run test asserts that running with the flag produces the same report but leaves both trees byte-identical to before, which is the property that makes the preview trustworthy.

Extending the project

Hashing instead of trusting mtime makes comparisons robust to regenerated files; a filter list excludes patterns; and a bidirectional mode adds conflict detection on top of the same plan structure. Each is a change to the planner, not the executor.