Multiple simultaneous access to file write in node.js gives file write error


I am using following code to write into a common file.

fs.appendFile('log.txt', str, function (err) {
    console.log("error writing file");

It is called at same time from multiple function calls. It completes file write operation correctly but still throws error "error writing file."

What is clean way to write/execute this code. I want each call to wait for I/O operation till already writing function finishes the job.

Problem courtesy of: Gaurav


Here's a basic example of a logging module.

var fs = require('fs');

var logStream = fs.createWriteStream('log.txt', {flags:'a'});

function log (str) {

module.exports = log;
Solution courtesy of: generalhenry


Actually you are missing an if - you should check if err is set.

fs.appendFile('log.txt', str, function (err) {
    if (err) console.log("error writing file");

Otherwise it will simply output your message because the callback is called after every append.

Discussion courtesy of: laktak

This recipe can be found in it's original form on Stack Over Flow.