Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access name of file within fs callback methods?

How do I get access to the the arguments of fs.read,fs.stat... methods from within a callback?

For instance if I want to process a file based on its size Following (coffeeScript) code snippet

#assuming test1.txt exists
filename = "./test1.txt"
fs.stat filename, (err, stats) ->
  data = filename:filename,size:stats.size
  console.log data
  #further process filename based on size
filename = "./test2.txt"

prints

{ filename: './test2.txt', size: 5 }

as filename is set to "./test2.txt". If I process/read the file using filename variable within fs.stat callback it would use test2.txt which is not intended.

What I expect to see within callback is

{ filename: './test1.txt', size: 5 }
like image 412
Prashant Bhate Avatar asked Jul 25 '12 21:07

Prashant Bhate


2 Answers

Don't think there's a way to do this right now. Might be a good thing to add to node at some point. If you're going to do this a lot you can put fs.stat in a friendly wrapper.

var friendlyStat = function(filename, callback){
    fs.stat(filename, function(err, stats){
        stats.filename = filename

        if(err) {
            callback(err);
        } else {
            callback(err, stats);
        }
    })
}

friendlyStat('test1.txt', function(err, stat){ console.log(stat.filename);});
friendlyStat('test2.txt', function(err, stat){ console.log(stat.filename);});
like image 135
Waylon Flinn Avatar answered Oct 04 '22 18:10

Waylon Flinn


You can use the synchronous fs.statSync() function if you can afford that, and that would help with your issue.

var filename = 'test1.txt';
var stat = fs.statSync(filename);
//code you were writing in callback comes here like the below:
console.log('Is ' + filename + ' a directory? ' + stat.isDirectory());
//Outputs 'Is test1.txt a directory? false'
like image 23
Vibhum Bhardwaj Avatar answered Oct 04 '22 20:10

Vibhum Bhardwaj