Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get access to a variable without nested callback?

I have a simple nested callback utilizing the Node FileSystem module and I'm having a hard time trying to get access to a variable that I feel is only made available due to the scope chain. My goal is to reduce nested callbacks as much as possible.

var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';

fs.readdir(directory, function(err, files) {
  files.forEach(function(file) {
    var filePath = directory + "/" + file;
    fs.readFile(filePath, function(err, data) {
      // I have access to filePath variable here.  This works just fine.
      console.log(filePath);
    });
  });
});

But this is what I would like to write instead:

var fs = require('fs');
var directory = '/Users/johndoe/desktop/temp';

fs.readdir(directory, processFiles);

function processFiles(err, files) {
  files.forEach(function(file) {
    var filePath = directory + "/" + file;
    fs.readFile(filePath, processSingleFile);
  });
}

function processSingleFile(err, data) {
  // how do I get the filePath variable here?
  console.log(filePath);
}

How do I get the filePath variable here in the second example?

like image 217
Kevin Avatar asked Sep 11 '26 07:09

Kevin


1 Answers

You can pass filePath as the first parameter to processSingleFile by binding it.

function processFiles(err, files) {
  files.forEach(function(file) {
    var filePath = directory + "/" + file;
    fs.readFile(filePath, processSingleFile.bind(this, filePath));
  });
}

function processSingleFile(filePath, err, data) {
  console.log(filePath);
}
like image 170
Raymond Chen Avatar answered Sep 13 '26 20:09

Raymond Chen