I think I'm having trouble with variable scope. Ultimately I'm creating a text log containing certain files and their date last modified using this code:
var fs = require('fs');
fs.writeFileSync('./scan_log.txt', "");
for(e in extensions){
createScanLogHeader(extensions[e]);
for (l in lines){
if(lines[l].indexOf(extensions[e]) > -1){
var fileMtime = getFileProperty(lines[l], "mtime");
fs.appendFileSync('./scan_log.txt', fileMtime + " " + lines[l] + "\n");
}
}
}
function getFileProperty(path, prop){
fs.stat(path, function(err, stats){
return stats.prop;
});
}
I get "undefined" prepended before the file path instead of the mtime file property. However if I put a console.log(stats.prop) in the getFileProperty function right above return stat.prop I do get the correct information logged to the console.
It's not a scope problem, it's that you're doing return stats.prop; from the callback of stat. Since stat is async, the callback's return value has no meaning (and if it did, it would still be happeng later, asynchronous to the call to getFileProperty).
If you absolutely, positively must have getFileProperty return the value, then you have to use statSync instead. The return has to be from getFileProperty, not the callback you pass stat.
Your stat call is asynchronous, and your getFileProperty function has no return value defined, so it returns undefined.
Either use statSync and return its value, or pass a callback to getFileProperty.
for (l in lines){
if(lines[l].indexOf(extensions[e]) > -1){
getFileProperty(lines[l], "mtime", function(path, prop) {
fs.appendFileSync('./scan_log.txt', prop + " " + path + "\n");
});
}
}
function getFileProperty(path, prop, fn){
fs.stat(path, function(err, stats){
fn(path, stats[prop])
});
}
Not familiar with the node.js framework, but a little googling shows that fs.stat(path,function) is asynchronous; so basically when you call
var fileMtime = getFileProperty(lines[l], "mtime");
you enter getFileProperty which immediately returns, and so the async return stats.prop basically goes nowhere...I think you should be using fs.statSync(path) insteaad, which is the synchronous version.