Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Variable scope trouble, I think

Variable scope trouble, I think

Problem

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.

Problem courtesy of: Jason Burgett

Solution

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])
    });
}
Solution courtesy of: the system

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Variable scope trouble, I think

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×