Friday 5 May 2017

fs.readFileSync only sometimes returns a valid string in specific circumstances

In my node application, I have an init function:

function init() {
    if (!fs.existsSync("../schedule.json"))
        fs.createReadStream('../template.json').pipe(fs.createWriteStream('../schedule.json'));

    var content = fs.readFileSync("../schedule.json", "utf8");

    return JSON.parse(content);
}

Whenever I try to run it from cmd or git bash it crashes because of the error:

SyntaxError: Unexpected end of JSON input

So I debugged it in vscode and found out that the variable content only contained an empty string which means that readFileSync is returning an empty string.

Now here is the weird thing; it never works if started in cmd or git bash (neither in regular mode or debug) or when started in debug mode in vscode but if I restart the debugger in vscode (not starting and stopping but actually hitting the restart button) then I get the correct content of the json file as a string returned from readFileSync about every other time.



via Cyber Sausage

No comments:

Post a Comment