Node - fs.writeFile creates an empty file

I am trying to write a new file inside a search callback.

The process takes in and object, walks through it for some data, creates a new array, and then writes that array to a JSON file. The writing part doesn't work that well ...

// onComplete is the callback, job is a returned object.
onComplete: function(job) {
    console.log("Creating file \"localize_template\"...");
    var fs = require('fs');
    var localArray = {};
    var foundEntries = job.matches;

    var stringCount = 0;

    // Drill down to the strings that matched the search.
    for (var foundEntry in foundEntries) {
        // Stay on target...
        if (foundEntries.hasOwnProperty(foundEntry)) {
            var singleEntry = foundEntries[foundEntry];
            // Almost...there...
            for( var match in singleEntry ) {
                if (singleEntry.hasOwnProperty(match)) {

                    // Direct hit!  We've drilled down to the match string itself.
                    var theMatch = singleEntry[match].match;

                    // Now, get the terms inside the strings that were referenced.
                    var terms = theMatch.match(/".*?"/g);

                    // Iterate through those strings and add them as entries in the localArray.
                    for( var i=0; i<terms.length; i++ ) {
                        var term = terms[i].replace(/"/g, '');

                        localArray[term] = 'xx:'+term;
                        stringCount++;
                    }
                }
            }
        }
    }

    fs.writeFile( 'i18n/localize_template.json', localArray, {encoding: 'utf8'}, function(err){
        console.log("File localize_template.json create successfully.");
        if(err) {
            throw err;
        } else {
           console.log("File localize_template.json create successfully.");
        }
    });    
}

      

The file is created but it is empty. I tried using a generic string Hello World!

instead localArray

for testing, but the file is still empty.

+3


source to share


4 answers


You need to use the synchronous version:



fs.writeFileSync("./output.txt", "file contents"); 

      

+4


source


To answer more clearly fs.writeFile

is asynchronous and the top level grunt stuff doesn't know to wait for asynchronous operations to start from onComplete

. You need to figure out how to tell that you have an asynchronous operation in progress other than this is a function that grunt-search

does not support
. Otherwise, when you return with onComplete

, it grunt-search

will mark the task as done immediately and grunt will exit, after which the node process will exit before the asynchronous write completes.

Another thought is to use grunt.file.write()

. This is a synchronous API, so you don't need to deal with the problem of not being able to tell that your task has not been completed. Also, using this API will make your code magically maintain the grunts parameter --no-write

since it doesn't work when the user requests a dry run.



onComplete: function (matches) {
    grunt.file.write('test', JSON.stringify(matches));
},

      

+3


source


Your problem must be that fs.writeFile is being run "asynchronously". Try changing localArray here (hardcode this to see if it works):

fs.writeFile( 'i18n/localize_template.json', localArray, callback)

      

And there it should work. Solution, I think you should use fs.writeFileSync or initialize localArray outside of the incomplete function before it starts up.

+2


source


Try to find out if your code has

process.exit ()

For some reason, I only have it in moderation for testing. If you do, please comment on this and you should be good to go. My version is v8.6.0.

0


source







All Articles