Passing additional parameters to the callback of fs.readFile in Node js

时间:2016-07-11 19:49:39

标签: javascript node.js asynchronous callback

Is it possible to pass additional parameters to the callback function of a fs.readFile. I have my code to read a directory and parse all the XML documents. I need to pass the filename down the callback chain for additional processing. As of now my code is

var fs = require('fs');
var path = require('path');

module.exports.extractXMLBody = function (dirPath, ext) {
    fs.stat(dirPath, function (err, stats) {
        if (stats.isDirectory()) {
            fetchFiles(dirPath, ext, function (listOfFiles) {
                _.each(listOfFiles, function (val, key) {
                    var completePath = dirPath + '/' + val;
                    var fileName = path.basename(val, path.extname(val))
                    // TODO : Figure out to pass additional parameters
                    fs.readFile(fullPath, parseXML);
                });
            });
        }
    });
}

Here parseXML is the callback i have defined as a separate function & I want to pass the variable newFileName to the callback function parseXML.

Note : If i write the callback as anonymous function, i can pass the access the variable but I'm trying to avoid the further nesting of callbacks.

2 个答案:

答案 0 :(得分:2)

No, you can't have additional values passed to the callback function since that is not supported by fs.readFile(). It will only pass back 2 values to the callback function at all times. It follows an error-first callback structure, so that means the first parameter will be an Error or null if one didn't occur and the next argument will contain the data of the file, if there is any.

If you want to access the fileName variable inside your callback for fs.readFile() then you would need to define it within the same scope where fs.readFile() is called. This would more or less require you to go with an anonymous function. However you should still name it for better Error StackTraces.

_.each(listOfFiles, function (val, key) {
  var completePath = dirPath + '/' + val;
  var fileName = path.basename(val, path.extname(val));

  fs.readFile(fullPath, function parseXML(err, data) {
    if(err) {
      console.log(err);
    }
    else {
      // parseXML and still have access to fileName
    }
  });
});

答案 1 :(得分:0)

实际上,您现在有一种方法可以做到。您可以使用.bind函数将变量传递给回调函数。 例如:

    for (file of files) {
      fs.readFile(`./${file}`, 'utf8', gotFile.bind({ "filename": file }))
}

在回调函数(在我的示例中为gotFile)中,您可以这样使用变量filename:

console.log(`Read ${this.file}.json`)