简体   繁体   中英

node.js nodeschool learnyounode need help understanding the code of the solution

Question - the exercise from NODESCHOOL.IO;LEARNYOUNODE;MAKE_IT_MODULAR reads directory and filters files by a given file extension - uses a module to do most of the work. Question on the added code referenced below. First time see this - but i take it from this example you are able to add code to an already defined function when you call it. But want to clarify if I understand the execution of it. Is it the callback function - noted below that allows this "added" code to be executed? Thanks

solution.js:

var filterFn = require('./solution_filter.js')
var dir = process.argv[2]
var filterStr = process.argv[3]

filterFn(dir, filterStr, function (err, list) {
if (err)
  return console.error('There was an error:', err)


// QUESTION ON THIS PART OF THE CODE - see below in the module part of the program

list.forEach(function (file) {
  console.log(file)
})

})


// THIS IS THE MODULE FOR THE PROGRAM

solution_filter.js:

// require file system module

var fs = require('fs')

module.exports = function (dir, filterStr, callback) {
var regex = new RegExp('\\.' + filterStr + '$')

fs.readdir(dir, function (err, list) {

// callback err if the readdir method fails 

  if (err)
    return callback(err)

  list = list.filter(function (file) {
    return regex.test(file)
  })

 // IS THIS CALLBACK SO IT LOOP AND IS ABLE TO EXECUTE ADDED CODE in the solution.js filterFn()

  callback(null, list)
  })
 }

Thinking about it as "adding code to an already defined function" isn't really accurate. You're passing in a completely different function as the callback parameter. The code in the module is written to expect that, and it invokes the function you pass in.

Your function doesn't have access to the code in the module, and the module doesn't have access to the code in your function.

Creating functions on-the-fly and passing them as parameters to other functions is a very common pattern in JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM