Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  2] [ 5]  / answers: 1 / hits: 18625  / 9 Years ago, wed, july 22, 2015, 12:00:00

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.


More From » node.js

 Answers
45

You need to use the synchronous version:



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

[#65720] Monday, July 20, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byron

Total Points: 616
Total Questions: 101
Total Answers: 91

Location: Reunion
Member since Wed, Apr 14, 2021
3 Years ago
byron questions
Wed, Jan 26, 22, 00:00, 2 Years ago
Sat, Jun 6, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
Wed, Sep 11, 19, 00:00, 5 Years ago
;