Skip to content Skip to sidebar Skip to footer

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

Solution 1:

You need to use the synchronous version:

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

Solution 2:

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));
},

Solution 3:

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.

Solution 4:

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.

Solution 5:

By 2020, in a async function, use await as follows:

try {
    // blah blah// Write data to the fileawait 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}`)
}

Post a Comment for "Node - Fs.writefile Creates A Blank File"