2

My code takes a line and tries to get an MP3 from Google translate with the line.

However, the loop is too fast for the Async function fs.exists(...) and only the last line in the array is fetched. I'm guessing the loop is changing the variables filename and line before they are even being requested.

What's a good work around to this? I could see using fs.existsSync(...) as one possible solution, but is there a better one?

for (var i = 0, length = lines.length; i < length; i++) {
    // Get the line in question
    var line = lines[i].trim();

    // The saving filename
    var filename = crypto.createHash('md5').update(line).digest('hex') + ".mp3";

    // Does the file exist?
    fs.exists(filename, function(exists) {
        console.log(line + "->" + filename);
        // We have to process it!
        if (!exists) {
            request
                .get({
                    'url': url,
                    'qs': {
                        'tl': lang,
                        'q': line,
                        'ie': 'UTF-8'
                    }
                })
                .on('error', function(error) {
                    console.error(error);
                })
                .on('response', function(response) {
                    if (response.statusCode != 200) {
                        console.error(response);
                    }
                })
                .pipe(fs.createWriteStream(filename));
        }
    });
}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Mikey A. Leonetti
  • 2,834
  • 3
  • 22
  • 36
  • 3
    [JavaScript closure inside loops](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – adeneo Mar 17 '15 at 14:56
  • 1
    Don't define a function inside a loop. It's a classic JS error that gets people (like me) over and over again. – Austin Mullins Mar 17 '15 at 14:58
  • 1
    This will be less of an issue if environments support [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let). http://stackoverflow.com/a/16661498/218196 – Felix Kling Mar 17 '15 at 15:04

0 Answers0