Sky Sky - 1 year ago 210
Node.js Question

nodejs write file frequently

I have a listener to listen for the change of content, once the content modified, it will emit the handler function:

$('#editor').on('onchange', () => changeHandler('...','...'));

function changeHandler(filePath, content){
var ws = fs.createWriteStream(filePath, 'utf8');

My problem is that the 'onchange' occurs too often, so 'write file' too often handles, it may lost data during the period.
Can someone give any suggestion?

Now I've changed code according the answers below looks like:

this.buffer = null; //used to cache

// once content changed, maybe too often
changeHandler() {
if (this.editor.curOp && {
var id = $('.nav-items .lk-hosts').attr('data-hosts-id');
var content = this.editor.getValue();
// cache data, not immediately write to file
this.buffer = {id: id, content: content};

setInterval(()=> {
// means there's data in cache
if (this.buffer !== null) {
let id =;
let content = this.buffer.content;
// reset cache to null
this.buffer = null;
// write file
this.writeContent(id, content, (err)=> {
}, 800);

Thanks all answers!

Answer Source

Why not simply build a buffer to collect written text then write to file only when you have a certain number of writes:

$('#editor').on('onchange', () => changeHandler('...','...'));

var writeBuffer = ''; // can also make this an array
var writeBufferSize = 0;
var filePath = 'path_to_file';
var ws = fs.createWriteStream(filePath, 'utf8');

function changeHandler(content){
    if (writeBufferSize == SOME_THRESHOLD) {
        writeBuffer = '';
        writeBufferSize = 0;
    } else {
        writeBuffer += content + '\n';

If you choose a write buffer threshold that's too big, you might want to delegate the write to some worker thread to be done in parallel, and in this case you can create another temporary write buffer to fill out while the original is being written, then switch the two.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download