How to access file name in fs callback methods?

How to access the arguments of methods , ... of the callback? fs.readfs.stat

For example, if I want to process a file by its size, the following code fragment (coffeeScript)

#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 }

the file name is set to "./test2.txt". If I process / read a file using the file name variable in the callback fs.stat, it will use test2.txtone that is not intended.

What I expect to see in the callback

{ filename: './test1.txt', size: 5 }
+5
source share
3 answers

, . - node. , fs.stat .

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);});
+7

, , , :

var files = [ 'path/to/file1.txt', 'path/to/file2.txt'],
    callback = function( filepath ) {
        return function( error, stat ) {
            console.log( filepath );
            console.log( error );
            console.log( stat )
        };
    };

    for ( var i = 0; i < files.length; i++ ) {
        fs.stat( files[ i ], callback( files[ i ] ) );
    }

callback . , fs.stat.

0

fs.statSync(), , .

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'
0

All Articles