KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've got a problem with this code in node.js. I want to recursively walk through a directory tree and apply the callback action to every file in the tree. This is my code at the moment: var fs = require("fs"); // General function var dive = function (dir, action) { // Assert that it's a function if (typeof action !== "function") action = function (error, file) { }; // Read the directory fs.readdir(dir, function (err, list) { // Return the error if something went wrong if (err) return action(err); // For every file in the list list.forEach(function (file) { // Full path of that file path = dir + "/" + file; // Get the file's stats fs.stat(path, function (err, stat) { console.log(stat); // If the file is a directory if (stat && stat.isDirectory()) // Dive into the directory dive(path, action); else // Call the action action(null, path); }); }); }); }; The problem is that in the for each loop stat is called for every file via the variable path . When the callback is called, path already has another value and so it dive s into the wrong directories or calls the action for the wrong files. Probably this problem could easily get solved by using fs.statSync , but this is not the solution I would prefer, since it is blocking the process.
Tags (comma-separated)
Save Edits
Cancel