Saturday, February 22, 2014

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

Thanks for the encouragement Micah Alcorn! I wrote to a file using node.js.

var fs = require('fs');

fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});

*source: http://nodejs.org/api/fs.html

I can also append data to the same file, through something like this:

var fs = require('fs');

fs.writeFile('message.txt', 'Hello Node', function(err) {
  if (err) throw err;
  console.log('It\'s saved!');
});

fs.appendFile('message.txt','data to append, function (err) {
  if (err) throw err;
  console.log('The "data to append" was appended to a file!');
});

If I want to instead take imput from the user and save it to a file all I have to do is:

var readline = require('readline');
var fs = require('fs');
var answer = 'this 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
  console.log("Thank you for your valuable feedback:", answer);

  rl.close();
})

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

*source: http://nodejs.org/api/readline.html

Except this does not work, maybe because answer in rl.question does not appear to be local in scope...because the output of fs.writeFile is 'this answer'.

No comments:

Post a Comment