0

I have file this piece of code:

var result = '';
     files.forEach(function (file) {

        fs.readFile(generateTemplatePath(fileType), 'utf-8', function (err, data) {
            if (err) {
                return console.log(err);
            }
            var fileString = fs.readFileSync(baseDir + fileType + '/' + file).toString();

            var content = escapeCharacters(fileString);

            result += data.replace('{{data}}', content);
            console.log(result);
        });
        console.log(result);
    });

Problem is, first console.log prints consecutive values, but second one prints empty string. How to pass result outside of forEachfor example as function's returnvalue?

dawidklos
  • 902
  • 1
  • 9
  • 32
  • `readFile` is asynchronous so any code *after* `fs.readFile` will run *before* the callback you passed to it. – Mike Cluck Jun 28 '16 at 17:31
  • The simplest solution is to embrace callbacks and do all your operations inside the callback instead of returning. You will probably want to use promises though if you want all of the callbacks to be executed in order. – 4castle Jun 28 '16 at 17:34
  • example: ```var result = ''; files.forEach(function (file) { var promise = return new Promise(function(resolve, reject) { fs.readFile(generateTemplatePath(fileType), 'utf-8', function (err, data) { if (err) { return console.log(err); } var fileString = fs.readFileSync(baseDir + fileType + '/' + file).toString(); var content = escapeCharacters(fileString); result += data.replace('{{data}}', content); resolve(result); console.log(result); }); }); promise.then(function(result) { console.log(result) }) });``` – Phillip Chan Jun 28 '16 at 17:54
  • @PhillipChan but if replace second console.log(result) with return result i get undefined – dawidklos Jun 28 '16 at 18:27

0 Answers0