To write on a file in Node.js this is the usual process:
var fs = require('fs'); //[...] fs.writeFile('log.txt', 'Hello', encoding='utf8', function (err) { if (err) throw err; });
But this would overwrite the content of the file and write 'Hello' in it. To append text on a file, recently Node added the following command to their APIs:
var fs = require('fs'); //[...] fs.appendFile('log.txt', 'Hello', encoding='utf8', function (err) { if (err) throw err; });
As you can see it works exactly like the writeFile function except that this would append 'Hello' at the end of the file. Moreover, if the file doesn't exist yet, it will create it for you. Pretty useful!
What I noticed while looking at the file that was filled in the meantime with IDs (I kept inspecting it through wc -l filename) is that sometimes it "blocked" itself on some values, and then after a while it added a bunch of IDs and then again it blocked, and so on. I was pretty frustrated by this, since I thought it was a problem of my topology. In the end I asked Google about the appendFile function, since I was interested in its performances and I found out that it is asynchronous. That means I never had any error concerning the odd behaviour it had, it was just because the execution of the function itself is asynchronous. Thus I searched for a synchronous way to append text on a file and on the Node API page I found this:
var fs = require('fs'); //[...] fs.appendFileSync('log.txt', 'Hello', encoding='utf8');
As you can see it works a little bit differently from what appendFile does: it doesn't take a callback function anymore. And that's it. Now it appends correctly each time the process receives a message, so I can better monitor what's going on.
Hello,
ReplyDeleteI had the same problem (needing to persist data without having to install a full-blown database) so I wrote a pure javascript database that can persist to a file (using the appendFile function). It provides the most common subset of MongoDB's API, for clean CRUD operations: https://github.com/louischatriot/nedb
Thanks for the pointer, looks awesome!
ReplyDelete@Masiar Thanx
ReplyDeleteThank you for your valuable information about the node.js development security this is an useful one keep sharing the post like this...
ReplyDeletenode.js development services
BULK SMS
ReplyDeleteDigital marketing
Connect with The Most Trusted BULKSMS Provider in India. Attractive Price with Guarantee 100% Delivery. Call :9907922122
Bulk SMS service simply means sending out a large number of SMS for delivery to targeted mobile numbers.
kuşadası transfer
ReplyDeletefoça transfer
alaçatı transfer
didim transfer
karşıyaka transfer
QU8H0C