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.
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.
Here's a basic example of a logging module.
var fs = require('fs');
var logStream = fs.createWriteStream('log.txt', {flags:'a'});
function log (str) {
logStream.write(str);
}
module.exports = log;