문제

I'm looking for a way to get information about the current written file in the callback, e. g. the full file name.

도움이 되었습니까?

해결책

The naive way of doing this would be:

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

The problem of above code is that if any other code has changed the filename variable by the time the callback of fs.readFile is called, the logged filename will be wrong.

Instead you should do:

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

Here, the filename variable becomes local to the makeInformFunction function, which makes the value of filename fixed for each particular invocation of this function. The makeInformFunction creates a new function with this fixed value for filename, which is then used as the callback.

Note that, filename within the makeInformFunction refers to a whole different variable than filename in the outer scope. In fact, because the argument name used in makeInformFunction uses the same name as the variable in the outer scope, this variable in the outer scope becomes entirely unreachable from within that function scope. If, for some reason, you want access to that outer variable, you need to choose a different argument name for the makeInformFunction.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top