मैं node.js. में इस कोड के साथ एक समस्या मिल गया है मैं रिकर्सिवली एक निर्देशिका वृक्ष के माध्यम से चलना और पेड़ में हर फाइल करने के लिए कॉलबैक action
लागू करना चाहते हैं।Node.js के साथ एक निर्देशिका चलना
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);
});
});
});
};
समस्या यह है कि प्रत्येक पाश के लिए में स्टेट चर path
के माध्यम से हर फ़ाइल के लिए कहा जाता है: इस पल में मेरी कोड है। जब कॉलबैक कहा जाता है, path
पहले से ही एक और मूल्य और गलत निर्देशिका में तो यह dive
रों है या गलत फ़ाइलों के लिए action
कहता है।
शायद इस समस्या को आसानी से fs.statSync
का उपयोग कर हल किया जा सकता है, लेकिन यह वह समाधान नहीं है जिसे मैं पसंद करूंगा, क्योंकि यह प्रक्रिया को अवरुद्ध कर रहा है।
अंतिम [एनपीएम पैकेज] (http://search.npmjs.org/#/dive) – pvorb
यह आपकी फ़ाइल के शीर्ष पर 'सख्त उपयोग "डालने से पकड़ा गया होगा। – Domenic
क्रॉस-प्लेटफ़ॉर्म संगतता के लिए, कच्चे '"/"' को जोड़ने के बजाय नोड के [path.join] (http://nodejs.org/api/path.html#path_path_join_path1_path2) फ़ंक्शन का उपयोग करें। –