How to access name of file within fs callback methods?

允我心安 提交于 2019-12-05 11:31:08
Waylon Flinn

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

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'

The accepted answer works great, but here's a solution I came up with when I wanted to loop through an array of files:

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

We're calling the callback function and passing it the filename as an argument. The function then returns the actual callback function which is used by fs.stat.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!