12 ms·
var array = []; client.addListener('message', function (from, to, text) { var time = Math.floor(new Date() / 1000); var obj = { nick: from,
by koolba 11y ago
var array = [];
client.addListener('message', function (from, to, text) {
var time = Math.floor(new Date() / 1000);
var obj = { nick: from, message: text };
var item = '\"' + time + '\"\:' + JSON.stringify(obj);
array.push(item);
fs.writeFile(file, '{' + array + '}\n', function() {
// console.log("updated");
});
});
This will buffer all the messages in memory (in the variable "array") and rewrite the file on every message. Besides the lack of atomicity mentioned in another comment, that's also really inefficient and will eventually run out of memory. Plus 1000 incoming messages will lead to 1000 sequential rewrites of the same file!
- IanCal 11y agoA useful file format to deal with this kind of problem is JSONL, which is just a list of newline separated json blobs. You can then simply append things to the file rather than having to write the whole thing each time.