Node js writting file

This is what it should do:

  1. If there is no html files make one and content of it should be "normal write" LINE 87 - 93

  2. If there is one with content, overwrite it with "overwrite" LINE 65 -75

  3. If there is one with no content, make the content "blank write" LINE 78 - 82

2 Works. 1 will make the html file but does not add content. 3 does not add content.

I have no idea why as the file writting part of all 3 are identical. Please help Thanks

HERE'S HE CODE:

if (htmlFILE) {
        log('INPUT'.red+' '+htmlFILE);
        fs.readFile(htmlFILE,'utf8',function(err,data) {
            if (err) {
                error(err);
            } else {
                if (data.length >= 1) {
                    terminal.question('Do you want to overwrite data in '+htmlFILE+'? [ Y or N ] ',function(answer){
                        terminal.close();
                        if (answer.toLowerCase() == 'y') {
                            log(' WRITING FILE '.inverse.cyan+' '+htmlFILE.yellow);
                            //WRITE INTO THE FILE HERE
                            fs.writeFile(htmlFILE,'overwrite');
                            log('overwritten');
                        } else {
                            log(' END PROCESS '.inverse.red);
                            process.exit();
                        }
                    });
                } else {
                    log(' WRITING FILE '.inverse.cyan+' '+htmlFILE.yellow);
                    //WRITE INTO THE FILE HERE
                    fs.writeFile(htmlFILE,'normal blank write');
                    log('blank write');
                    process.exit();
                }
            }
        });
    } else {
        //WRITE TO FILE HERE
        log('INPUT'.red+' none');
        htmlFILE = "Backkick "+Math.random()+'.html';
        log('info'.inverse.red+' '+'create '+htmlFILE);
        fs.writeFile(htmlFILE,'normal write');
        log('normal write');
        process.exit();
    }

}
});

The big difference is that after fs.writeFile(htmlFILE,'overwrite'); (the one which is working) you don't have process.exit();.

writeFile is an asynchronous function. If you call process.exit() right after, you don't let nodejs the time to write content into the file.

Try something like:

fs.writeFile(htmlFILE,'normal blank write', function(err){
    if(!err)
        log('blank write');
    else
        log('error: ' + err);
    process.exit();
);

And you probably even can remove all process.exit();