JohnRobertPett
JohnRobertPett

Reputation: 1183

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?

Upvotes: 20

Views: 29740

Answers (4)

grant-wilson
grant-wilson

Reputation: 56

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

Upvotes: 4

Purushoth.Kesav
Purushoth.Kesav

Reputation: 665

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.

Upvotes: 2

Matt Horrigan
Matt Horrigan

Reputation: 31

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.

Upvotes: 3

samiq
samiq

Reputation: 2974

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

Upvotes: 48

Related Questions