Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top