CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-walkdir

Directory traversal library that walks file system trees with multiple interface options including callback, event emitter, synchronous, and promise-based patterns.

Pending
Overview
Eval results
Files

sync-operations.mddocs/

Synchronous Operations

Synchronous directory traversal that blocks execution until all paths are discovered and returned as a complete result set.

Capabilities

Sync Function

Synchronously walk a directory tree and return all results immediately.

/**
 * Synchronously walk directory tree and return all paths
 * @param {string} path - Directory path to walk
 * @param {WalkOptions} [options] - Walk configuration options
 * @param {WalkEventListener} [eventListener] - Optional callback for each path found
 * @returns {string[]|Object<string,fs.Stats>} - Array of paths or object mapping paths to stats
 */
function walkdir.sync(path, options, eventListener);

Return Types:

  • Default: string[] - Array of all discovered paths
  • With return_object: true: {[path]: fs.Stats} - Object with paths as keys and stat objects as values

Usage Examples:

const walkdir = require('walkdir');

// Basic sync - returns array of paths
const paths = walkdir.sync('./my-directory');
console.log('Found', paths.length, 'items');
paths.forEach(path => console.log(path));

// Sync with callback - still returns array, but calls function for each path
const paths2 = walkdir.sync('./my-directory', (path, stat) => {
  if (stat.isFile()) {
    console.log('File:', path, 'Size:', stat.size);
  }
});

// Sync with options - return object format
const stats = walkdir.sync('./my-directory', { return_object: true });
for (const [path, stat] of Object.entries(stats)) {
  console.log(path, {
    type: stat.isDirectory() ? 'dir' : 'file',
    size: stat.size,
    modified: stat.mtime
  });
}

// Sync with depth limit
const shallowPaths = walkdir.sync('./my-directory', { max_depth: 2 });
console.log('Paths within 2 levels:', shallowPaths);

// Sync with filtering
const jsFiles = walkdir.sync('./src', {
  filter: (dir, files) => files.filter(f => f.endsWith('.js'))
});

// Memory-optimized sync (no return array built)
walkdir.sync('./huge-directory', { no_return: true }, (path, stat) => {
  // Process each path immediately - no memory buildup
  if (stat.isFile() && stat.size > 1024 * 1024) {
    console.log('Large file:', path, stat.size);
  }
});

Sync with Return Object

When return_object: true is specified, the sync function returns an object instead of an array.

/**
 * Synchronously walk directory with object return format
 * @param {string} path - Directory path to walk  
 * @param {WalkOptions & {return_object: true}} options - Options with return_object flag
 * @param {WalkEventListener} [eventListener] - Optional callback for each path
 * @returns {Object<string,fs.Stats>} - Object mapping paths to their fs.Stats objects
 */
function walkdir.sync(path, {return_object: true, ...options}, eventListener);

Usage Example:

const stats = walkdir.sync('./project', { 
  return_object: true,
  max_depth: 3 
});

// Access stat information directly
for (const [path, stat] of Object.entries(stats)) {
  if (stat.isFile() && path.endsWith('.json')) {
    console.log('JSON file:', path, 'Modified:', stat.mtime);
  }
}

// Check if specific path exists in results
if (stats['./project/package.json']) {
  console.log('Found package.json');
}

Memory Optimization

For very large directory trees, use no_return: true to prevent memory buildup.

/**
 * Synchronously walk directory without building result collection
 * @param {string} path - Directory path to walk
 * @param {WalkOptions & {no_return: true}} options - Options with no_return flag  
 * @param {WalkEventListener} eventListener - Required callback to process each path
 * @returns {null} - No return value when no_return is true
 */
function walkdir.sync(path, {no_return: true, ...options}, eventListener);

Usage Example:

// Process massive directory without memory overhead
let fileCount = 0;
let totalSize = 0;

walkdir.sync('/var/log', { no_return: true }, (path, stat) => {
  if (stat.isFile()) {
    fileCount++;
    totalSize += stat.size;
  }
});

console.log(`Processed ${fileCount} files, total size: ${totalSize} bytes`);

Error Handling

Synchronous operations handle errors by:

  • Target path errors: Throw exceptions immediately
  • Nested path errors: Skip the problematic path and continue (no exception thrown)
  • Permission errors: Skip inaccessible directories and continue traversal
try {
  const paths = walkdir.sync('./some-directory');
  console.log('Success:', paths.length, 'items found');
} catch (error) {
  console.error('Failed to read target directory:', error.message);
}

Performance Considerations

  • Blocking: Sync operations block the event loop until completion
  • Memory usage: Without no_return: true, all paths are stored in memory
  • Best for: Small to medium directory trees, build scripts, CLI tools
  • Avoid for: Large directory trees, server applications, real-time applications

Install with Tessl CLI

npx tessl i tessl/npm-walkdir

docs

async-operations.md

core-walking.md

events-control.md

index.md

options-configuration.md

sync-operations.md

tile.json