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 write
Your problem should be that the fs.writeFile starts "asynchronous". Try to change the localArray in here (hardcode it to see if it works):
fs.writeFile( 'i18n/localize_template.json', localArray, callback)
And there it should work. The solution i think it is that you should use fs.writeFileSync, or to initialize the localArray outside the oncomplete function, before it starts.
Try to find out if your code has
process.exit()
For some reason, I have one temperately for testing only. If you do, comment out this one and you will be good to go. My version is v8.6.0.
By 2020, in a async
function, use await
as follows:
try {
// blah blah
// Write data to the file
await fs.writeFile(path, data, function (err) {
if (err) {
console.error(`An error occurred while writing data to the file: ${err.message}`)
throw err
}
})
// blah blah
}
catch(err) {
console.error(`An error occurred while writing data to the file: ${err.message}`)
}
You need to use the synchronous version:
fs.writeFileSync("./output.txt", "file contents");
To answer more clearly, fs.writeFile
is asynchronous and the top level grunt stuff doesn’t know to wait for asynchronous operations started by onComplete
. You need to figure out how to tell grunt that you have an unfinished asynchronous operation, except this is a feature that grunt-search doesn’t support. Otherwise, when you return from onComplete
, grunt-search
will mark the task as done immediately and grunt will exit causing the node process to exit before the asynchronous write completes.
Another thought is to use grunt.file.write(). This is a synchronous API, so it won’t require you solve the problem of being unable to tell grunt that your task isn’t done. Also, using this API will make your code magically support grunt’s --no-write
option by being a no-op when the user requests a dry run.
onComplete: function (matches) {
grunt.file.write('test', JSON.stringify(matches));
},