javascript - Variable not being remembered in JSON -
i have code loops through directory , retrieves file name of each file. code retrieves contents of each file (usually number or short text).
var config = {}; config.liveprocvalues = {}; var path = require('path'); walk = function(dir, done) { var results = {}; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.foreach(function(file) { file = path.resolve(dir, file); fs.stat(file, function(err, stat) { if (stat && stat.isdirectory()) { walk(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { fs.readfilesync(file, 'utf8', function(err, data) { if (err) { contents = err; } else { contents = data; } console.log(filename + " - " + contents); filename = file.replace(/^.*[\\\/]/, ''); config.liveprocvalues[filename] = contents; }); the console.log line outputs right information, when trying store json:
config.liveprocvalues[filename] = contents; it remember information.
walk("testdirectory", function(err, results) { if (err) throw err; }); // output configuration console.log(json.stringify(config, null, 2));
you have make sure accessing data after filesystem traversed. in order have move console.log into walk callback:
walk("testdirectory", function(err, results) { if (err) throw err; // output configuration console.log(json.stringify(results, null, 2)); }); see why variable unaltered after modify inside of function? - asynchronous code reference more info.
that alone won't solve issue though, since have couple of logic errors in code. trying treat object array (results.concat) , not calling done when done (in particular, not calling done after finished reading files in directory).
here version should come closer want.
this uses object.assign merge 2 objects, not available in node yet, can find modules provide same functionality.
note thats removed whole config object. it's cleaner if work results.
var path = require('path'); function walk(dir, done) { var results = {}; fs.readdir(dir, function(err, list) { if (err) return done(err); if (!list.length) return done(null, results); var pending = list.length; list.foreach(function(file) { file = path.resolve(dir, file); fs.stat(file, function(err, stat) { if (stat && stat.isdirectory()) { walk(file, function(err, res) { if (!err) { // merge recursive results object.assign(results, res); } if (!--pending) done(null, results); }); } else { fs.readfile(file, 'utf8', function(err, data) { var contents = err || data; console.log(file + " - " + contents); file = file.replace(/^.*[\\\/]/, ''); // assign result `results` instead of shared variable results[file] = contents; // need call `done` if there no more files read if (!--pending) done(null, results); }); } }); }); }); } but instead of writing own walk implementation, use existing package.
Comments
Post a Comment