Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - node - fs.writeFile creates a blank file

I'm trying to write a new file inside a grunt-search callback.

The process takes and object, traverses through it for some data, creates a new array, and then writes that array to a JSON file. The writing part isn't working out so 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 being created, but it's blank. I've tried using a generic Hello World! string instead of localArray to test, but the file is still blank.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use the synchronous version:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...