Saturday, February 22, 2014

Reading from the User and Writing to a File in Node.js (part 3)

// Thanks for the encouragement Micah Alcorn! I wrote to a file using node.js.
// Now I am embedding the write in a function within readline. Due to variable
// scope, I have two outputs for the variable answer. One is 'the wrong answer'
// and the other is what I choose.

readline = require('readline');

var fs = require('fs');

var answer = 'the wrong answer';

var rl = readline.createInterface({

  input: process.stdin,

  output: process.stdout,

});

rl.question("What do you think of node.js?", function(answer) {

  // TODO: Log the answer in a database
  // Hmm ... I wonder what happens if I write to the file here...

write(answer);
//  fs.writeFile('read_write_node_embed.txt', answer, function(err) {
 
//    if (err) throw err;
  
//    console.log('It\'s saved!');

//});

// The end of the writing to the file

  console.log("Thank you for your valuable feedback:", answer);

  rl.close();

})

function write(answer) {
fs.writeFile('write_answer.txt', answer , function(err) {

  if (err) throw err;

  console.log('It\'s saved!');

});
}

fs.writeFile('wrong_answer.txt', answer, function(err) {

  if (err) throw err;

  console.log('It\'s saved!');

});

No comments:

Post a Comment