如何在fs回调方法中访问文件名? [英] How to access name of file within fs callback methods?

查看:99
本文介绍了如何在fs回调方法中访问文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何访问 fs.readfs.stat ...的参数回调中的方法?

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

例如,如果我想根据文件的大小处理文件 以下(coffeeScript)代码段

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"

打印

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

,因为文件名设置为"./test2.txt".如果我在fs.stat回调中使用filename变量处理/读取文件,它将使用test2.txt这不是预期的.

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 }

推荐答案

不要认为现在有一种方法可以做到这一点.在某个时候添加到节点可能是一件好事.如果要执行很多操作,可以将fs.stat放入友好的包装中.

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

这篇关于如何在fs回调方法中访问文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆