【问题标题】:Node.js fs.readfile/Asynchronous file access: Get the current file in the callbackNode.js fs.readfile/异步文件访问:在回调中获取当前文件
【发布时间】:2014-04-02 13:44:57
【问题描述】:

我正在寻找一种方法来获取有关回调中当前写入文件的信息,例如。 G。完整的文件名。

【问题讨论】:

    标签: node.js file asynchronous readfile fs


    【解决方案1】:

    这样做的天真方法是:

    var filename = "/myfile.txt"
    fs.readFile(filename, function(err, contents) { 
       console.log("Hey, I just read" + filename)
       if(err) 
         console.log("There was an error reading the file.")
       else
         console.log("File contents are " + contents)
    })
    

    上述代码的问题是,如果在调用fs.readFile 的回调时,任何其他代码更改了filename 变量,则记录的文件名将是错​​误的。

    你应该这样做:

    var filename = "/myfile.txt"
    fs.readFile(filename, makeInformFunction(filename))
    function makeInformFunction(filename) {
      return function(err, contents) {
        console.log("Hey, I just read" + filename)
        if(err) 
          console.log("There was an error reading the file.")
        else
          console.log("File contents are " + contents)    
      }
    }
    

    这里,filename 变量成为makeInformFunction 函数的局部变量,这使得filename 的值对于该函数的每个特定调用都是固定的。 makeInformFunctionfilename 创建一个具有此固定值的新函数,然后将其用作回调。

    请注意,makeInformFunction 内的 filename 指的是与外部范围内的 filename 完全不同的变量。事实上,因为makeInformFunction 中使用的参数名称与外部作用域中的变量使用相同的名称,所以外部作用域中的这个变量在该函数作用域内变得完全不可访问。如果出于某种原因,您想要访问该外部变量,则需要为 makeInformFunction 选择不同的参数名称。

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 2018-05-04
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多