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