fs.writeFile has no errors, but fails to write file

JohnRobertPett picture JohnRobertPett · Mar 27, 2014 · Viewed 12k times · Source

I am using node.js, trying to save a file, no errors are thrown, yes the image won't save. This is how I am saving the file:

var url = 'captures/' + getFileName() + '.png';

    fs.writeFile(url, base64, 'base64', function(err) {

        if(err) {
            console.log(err);
        } else {
            console.log("The file was saved!");
        }
    });

With a helper to make the file names for me:

function getFileName(){
    var d = new Date()
    return d.getMonth()+'-'+d.getDate()+'-'+d.getYear()+'-'+d.getHours()+'-'+d.getMinutes()+d.getSeconds();
}

Anyone had trouble with this?

Answer

samiq picture samiq · May 5, 2017

the problem is because this call is async and probably is loosing the context right after, I was able to fix it on my end by using fs.writeFileSync which does it synchronously. hope this helps