node - fs.writeFile creates a blank file
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.
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));
},