admin管理员组

文章数量:1429613

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 pletePath = 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.

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 pletePath = 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.

Share Improve this question asked Jul 11, 2016 at 19:49 Vivian Ajay MonisVivian Ajay Monis 1342 silver badges6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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 pletePath = 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
    }
  });
});

Actually, there's a way for you to do it now. You can use the .bind function to pass down a variable to your callback function. Eg:

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

And in your callback function (gotFile in my example), you van use the variable filename as such:

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

As @Aditya mented, .bind() solves the problem but the provided code didn't work for me so I got it to work like this:

fs.readFile(fullPath, parseXML.bind(null, additionalParameter))
const parseXML = (additionalParameter, error, fileContents) => {
  console.log(additionalParameter)
}

本文标签: javascriptPassing additional parameters to the callback of fsreadFile in Node jsStack Overflow