{"id":15925,"library":"walk","title":"Node.js File System Directory Walker","description":"The `walk` package for Node.js provides a comprehensive utility for traversing file system directories, drawing inspiration from Python's `os.walk` function. It primarily operates asynchronously using the EventEmitter pattern, allowing for event-driven processing of files and directories as they are discovered. The library, currently at version 2.3.15, also includes a synchronous counterpart. Key features include built-in flow control and an optimization strategy that minimizes the number of open file descriptors, making it suitable for environments with traditional hard disks. However, it's important to note that the package was initially developed during the Node.js v0.x era and has remained largely unchanged for approximately a decade. Consequently, its API design reflects an older Node.js paradigm. The author now explicitly recommends considering `@root/walk` as a more modern, simpler, and faster alternative for new projects, indicating that `walk` is largely in a maintenance or superseded state rather than active development.","status":"maintenance","version":"2.3.15","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","util","os","sys","fs","walk","walkSync"],"install":[{"cmd":"npm install walk","lang":"bash","label":"npm"},{"cmd":"yarn add walk","lang":"bash","label":"yarn"},{"cmd":"pnpm add walk","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package is primarily designed for CommonJS. For ESM, consider using `@root/walk` or configuring Node.js for CJS-ESM interop.","wrong":"import walkModule from 'walk';","symbol":"walk (module object)","correct":"const walkModule = require('walk');"},{"note":"The `walk` function is a method on the module's default export. Direct ESM `import` statements will typically fail in modern Node.js environments without specific CJS interop configuration.","wrong":"import { walk } from 'walk';","symbol":"walk (asynchronous function)","correct":"const { walk } = require('walk');"},{"note":"The `walkSync` function is also a method on the module's default export. It uses synchronous `fs` methods but its `EventEmitter` behavior relies on `process.nextTick()`, meaning truly blocking behavior requires `options.listeners`.","wrong":"import { walkSync } from 'walk';","symbol":"walkSync (synchronous function)","correct":"const { walkSync } = require('walk');"}],"quickstart":{"code":"const walk = require('walk');\nconst fs = require('fs');\nconst path = require('path');\n\nconst testDir = path.join(__dirname, 'temp_walk_dir');\nconst subDir = path.join(testDir, 'sub_dir');\nconst file1 = path.join(testDir, 'file1.txt');\nconst file2 = path.join(subDir, 'file2.txt');\n\n// Setup: Create a temporary directory structure\nfs.mkdirSync(testDir, { recursive: true });\nfs.mkdirSync(subDir, { recursive: true });\nfs.writeFileSync(file1, 'content for file1');\nfs.writeFileSync(file2, 'content for file2');\n\nconsole.log(`Starting walk in: ${testDir}`);\n\nlet filesFound = [];\nlet directoriesFound = [];\nlet errorsEncountered = [];\n\nconst options = {};\nconst walker = walk.walk(testDir, options);\n\nwalker.on('file', function (root, fileStats, next) {\n  filesFound.push(path.join(root, fileStats.name));\n  // console.log(`Found file: ${path.join(root, fileStats.name)}`);\n  next(); // Crucial to call next() to continue the walk\n});\n\nwalker.on('directory', function (root, dirStats, next) {\n  directoriesFound.push(path.join(root, dirStats.name));\n  // console.log(`Found directory: ${path.join(root, dirStats.name)}`);\n  next(); // Crucial to call next() to continue the walk\n});\n\nwalker.on('errors', function (root, nodeStatsArray, next) {\n  nodeStatsArray.forEach(nodeStats => {\n    errorsEncountered.push({ path: path.join(root, nodeStats.name), error: nodeStats.error ? nodeStats.error.message : 'Unknown error' });\n  });\n  console.error(`Errors encountered in ${root}:`, errorsEncountered);\n  next(); // Crucial to call next() to continue the walk\n});\n\nwalker.on('end', function () {\n  console.log('\\n--- Walk Complete ---');\n  console.log('Files found:', filesFound.sort());\n  console.log('Directories found:', directoriesFound.sort());\n  if (errorsEncountered.length > 0) {\n    console.error('Final errors summary:', errorsEncountered);\n  }\n\n  // Cleanup: Remove the temporary directory\n  fs.rmSync(testDir, { recursive: true, force: true });\n  console.log('\\nTemporary directory cleaned up.');\n});\n","lang":"javascript","description":"Demonstrates asynchronous directory traversal, creating a temporary file structure, collecting file and directory paths via EventEmitter callbacks, and cleaning up afterwards."},"warnings":[{"fix":"For new projects or refactoring, install and use `@root/walk` instead: `npm install @root/walk`.","message":"The package author explicitly recommends migrating to `@root/walk` for new projects due to its simpler, faster, and more modern design. While `walk` remains functional, it is considered superseded.","severity":"deprecated","affected_versions":">=2.0.0"},{"fix":"Use `const walk = require('walk');` in CommonJS modules. For ESM projects, consider using `@root/walk` or configuring `package.json` with `\"type\": \"commonjs\"` or explicit `.cjs` file extensions.","message":"This package was developed for CommonJS environments (`require`). Attempting to use `import` statements directly in an ESM module without specific Node.js loader configuration for CJS interop will result in errors.","severity":"gotcha","affected_versions":">=0.0.0"},{"fix":"When using `walkSync`, provide event handlers via the `options.listeners` object: `walk.walkSync(path, { listeners: { file: (r, s, n) => { /*...*/ n(); } } });`","message":"The `walkSync` function, despite using synchronous `fs` methods, still uses `EventEmitter` internally which relies on `process.nextTick()`. For truly synchronous, blocking behavior where control flow should not yield, `options.listeners` must be used instead of `.on()` event handlers.","severity":"gotcha","affected_versions":">=0.0.0"},{"fix":"Ensure `next()` is called at the end of all `walker.on('event', function(root, stats, next) { ... next(); });` callbacks.","message":"For asynchronous `walk` operations, it is crucial to call `next()` in every `file`, `directory`, and `errors` event handler. Failing to call `next()` will halt the directory traversal indefinitely, as it acts as a flow control mechanism.","severity":"gotcha","affected_versions":">=0.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"If in CommonJS, use `const walk = require('walk');`. If in ESM, consider using `@root/walk` or explicitly configuring Node.js to handle CommonJS imports within an ESM context (e.g., using a `.cjs` file extension or `package.json` `exports` field).","cause":"Attempting to use `import walk from 'walk';` or `import { walk } from 'walk';` in a Node.js environment configured for CommonJS, or in an ESM file without proper CJS interop.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"For `walkSync`, pass event handlers via the `options.listeners` object instead of calling `.on()` on the returned value. Example: `walk.walkSync(path, { listeners: { file: (r, s, n) => { /*...*/ n(); } } });`","cause":"This error occurs when attempting to attach event listeners (`.on()`) directly to the result of `walk.walkSync()`. The synchronous walker's primary event mechanism is through `options.listeners`, not the `EventEmitter` interface returned by `walk.walkSync` (which doesn't return an EventEmitter).","error":"TypeError: walker.on is not a function"}],"ecosystem":"npm"}