I am working through the learnyounode tutorials and came across this interesting bit and I am trying to figure out how to handle scope when you use a variable as a callback function:
The following code works:
module.exports = function(filePath, fileExtention, callback){
  fs.readdir(filePath, function (err, list){
    if(err) return callback("Something went wrong", null) 
    var fileArray = []
    list.forEach(function(file){
      if(file.indexOf('.' + fileExtention) > -1) fileArray.push(file)
    })
    return callback(null, fileArray)
  })
}
While this code throws an exception of fileExtention not defined:
module.exports = function(filePath, fileExtention, callback){
  fs.readdir(filePath, cb)
}
var cb = function (err, list){
  if(err) return callback("Something went wrong", null) 
  var fileArray = []
  list.forEach(function(file){
    if(file.indexOf('.' + fileExtention) > -1) fileArray.push(file)
  })
  return callback(null, fileArray)
}
I am trying to understand why that variable is out of scope for the second call back function that is defined as cb and what I would do to fix this, as the signature of that callback is fixed.
Would the solution be make a local variable that is set to the fileExtention parameter?
This works, however I do not know if it is the proper way to handle the callback being passed into the module to maintain scope:
var fs = require('fs')
var fe = ""
var cb;
module.exports = function(filePath, fileExtention, callback){
  fe = fileExtention
  cb = callback;
  fs.readdir(filePath, findFiles)
}
var findFiles = function (err, list){
  if(err) return cb("Something went wrong", null) 
  var fileArray = []
  list.forEach(function(file){
    if(file.indexOf('.' + fe) > -1) fileArray.push(file)
  })
  return cb(null, fileArray)
}
 
     
     
     
    