NodeJs: fs.appendFile function seems to miss last String given

1.2k Views Asked by At

I'm new to nodejs I was trying the append function. When I run below code that simply takes User input after prompting him, about fav singer and puts in a file with singer name. And appending fav songs, It seems if user entered exit it should be append it to the file but, its not??? Meanwhile if its change to appendFileSync (Synchronous version of the fn) exit is added??

Code:

var readline = require ('readline');
var fs = require('fs');
var rl = readline.createInterface(process.stdin, process.stdout);
var singer = {
  name:'',
  songs: []
};

rl.question("What is your fav singer? ", function(answer) {
  singer.name = answer;

  //creating a file for this singer
  fs.writeFileSync(singer.name+".md", `${singer.name}\n====================\n\n`); 

  rl.setPrompt(`What's your fav songs for ${singer.name} ?`);
  rl.prompt();

  rl.on('line', function(song) {
    singer.songs.push(song.trim());
    fs.appendFile(singer.name+".md", `* ${song.trim()} \n`);
    //***** WHY IF ITS EXIT ITS NEVER APPEND IT TO THE FILE
    console.log(`* ${song.trim()} \n`);

    if (song.toLowerCase().trim() === 'exit') {
      fs.appendFile(singer.name+".md", "Bye"); 
      //***** WHY ITS NEVER APPEND IT TO THE FILE
      rl.close();       
    } else {
      rl.setPrompt(`what else would ${singer.name} say? ('exit'to leave)`);
      rl.prompt();
    }
  });
});

rl.on ('close', function() {
  console.log ("%s is a real person that says %j", singer.name, singer.songs);
  process.exit();
});
1

There are 1 best solutions below

1
Vlad Churakov On

Because fs.appendFile is asynchronous. When you call it, io operations are queued only. Unfortunately, your script exits before the real io-operations happen.

So. you have to use either fs.appendFileSync or fs.appendFile with callback (the 3rd argument) and when the callback is called, do all further activities.