fs.writeFile not working inside .then


#1

This works as expected

From http://stackoverflow.com/questions/2496710/writing-files-in-node-js

var fs = require('fs');
fs.writeFile("myFile", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

But when inside part of a .then call

where myExternalFunction returns some XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:users xmlns:ns2="id


 myExternalFunction()
    .then(txt => fs.writeFile("myXML", txt, function(err){ //txt is of type string
        if (err) {
            return console.log("Error in saving XML file reason : ", err);
        }
        console.log("The XML file was saved");
    })
    )

myXML is now never generated but I still get

"The XML file was saved"

to display

Or do I need writeFileAsync?


#2

You have to learn to debug instead of rushing immediately into meteor forums. Also, software tends to work as specified more often than not : if fs.writeFile had issues with promises, then you would probably find mention of that online.

“The XML file was saved”

This means the application entered into the .then code

Print err and txt to see what they say.

Or do I need writeFileAsync?

writeFile is alredy async. The sync version is writeFileSync.

Also, try replacing writeFile by writeFileAsync to see what happens.