Bdfy Bdfy - 1 month ago 6
Node.js Question

How to append string to file?

I have a several processes node.js. I want to only add one string to one file in each request ( like log file in nginx, apache, etc ). What is the best way do it ?
Simple:

fs.open(file, "a", 0744, function (err, fd) {
if (err) throw err;
fs.write(fd, data, null, 'utf8', function (err, written) {
if (err) throw err;
});
});


or else ?

Answer

This will work, however it may not be the best solution if it is constantly opening and closing the file. For something with quicker writes I would try benchmarking it against fs.createWriteStream, especially because this gives you a scope you can use in routes.

var fs = require("fs");

   //set dummy data as random number
var data = Math.floor(Math.random()*11);
   //Set our log file as a writestream variable with the 'a' flag
var logFile = fs.createWriteStream('log.txt', {
  flags: "a",
  encoding: "encoding",
  mode: 0744
})
   //call the write option where you need to append new data
logFile.write(new Date().toSting + ': ' data);
logFile.write(new Date().toSting + ': ' data);