How to continuously read from a file in JavaScript without killing my CPU?

The title pretty much says it all. I’m working on an addon for an electron app, and I want to change certain settings based on what is written to a file on my local machine. I tried the following but it eats up an unhealthy chunk of my CPU.

var filepath = "/path/to/file";

const fs = require('fs');

var i = 1;

function readlines(file) {

const data = fs.readFileSync(file, 'UTF-8');
return data;
}

while( i > 0){
    signal = readlines(filepath);

    if ( signal == "hide" ) {
        console.log("hidden");
    } else if ( signal == "show" ){
        console.log("showing")
    }
};

Any help would be greatly appreciated!

25 thoughts on “How to continuously read from a file in JavaScript without killing my CPU?”

Leave a Comment