I've stubled upon a function (here on SO) which writes a file, but makes sure to not overwrite a file:
function writeFile(i){
var i = i || 0;
var fileName = 'a_' + i + '.jpg';
fs.exists(fileName, function (exists) {
if(exists){
writeFile(++i);
} else {
fs.writeFile(fileName);
}
});
}
Now there is an interesting comment below which says:
Minor tweak: Since JavaScript doesn't optimize tail recursion away, change
writefile(++i)
toprocess.nextTick(function(i) {writefile(++i);});
that will keep your stack from blowing up if you have to go through lots of file names.
Please explain. How does process.nextTick
prevent the stack from blowing up?
Update: Turns out the assumption in the comment was wrong! Anyway, cases do exist where process.nextTick
plays a role in preventing a stack overflow (see examples in accepted answer).