Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 612
JohnRobertPett Avatar asked Mar 27 '14 22:03

JohnRobertPett


People also ask

Does FS writeFile overwrite?

fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.

What is the difference between writeFile and writeFileSync?

The only difference between writeFile and writeFileSync is in catching and handling the errors; otherwise, all parameters mentioned are available in both functions.

Does FS writeFile create a file?

The fs. writeFileSync() is a synchronous method. The fs. writeFileSync() creates a new file if the specified file does not exist.

Is FS writeFile async?

writeFile() is an asynchronous method for writing data in files of any type.


2 Answers

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

like image 140
samiq Avatar answered Oct 08 '22 06:10

samiq


Add a console.log('captures/' + getFileName()) just to make sure your file name is correct. When I had this problem it turned out that I had a problem with the file path/name and node just wasn't throwing me an error to explain.

like image 42
Matt Horrigan Avatar answered Oct 08 '22 05:10

Matt Horrigan