'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?



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

If you want to write your file asynchronously, try using fs/promises instead of fs.

const { writeFile } = require("fs/promises");

(async () => {
    await writeFile('myFile.txt', 'my content', (err) => {});
})();

writeFile from fs is void. It will execute asynchronously but not in the async-await meaning. writeFile from fs/promises returns a Promise so async-await will work as expected.

Learn more here: https://nodejs.org/api/fs.html#callback-example

Solution 4:[4]

For Typescript version, Just sharing my experience here, In my use case had a JSON file where I used to store some temporary data read it and make some changes and update it and store that updated data to same JSON file will be used for next cycle. fs.writeFile was not throwing any error at same time it was not updating my JSON file where as JS version worked well, Then I realized that typescript made these changes in my root or src directory. Created another JSON file there.

Solution 5:[5]

There might be a permission issue.

go inside the directory that you are saving your files and then

sudo chmod 777 .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 samiq
Solution 2 Matt Horrigan
Solution 3 g_michael_w
Solution 4 CrazyKP
Solution 5 TheEhsanSarshar