1

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();
});
thanksd
  • 54,176
  • 22
  • 157
  • 150

1 Answers1

1

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.

Vlad Churakov
  • 350
  • 2
  • 7
  • Thank You fro your reply,When I run the app I enter Lets say --> MJ, then Beat it , then Black or White, then exit (output file has 1st mentioned two songs/but exit isn't written. IO Queued only, you mean it exit before the re actually implemented. – Ahmed Darweesh Jan 27 '16 at 09:06